欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > wordpress按分类ID调用最新、推荐、随机内容

wordpress按分类ID调用最新、推荐、随机内容

2025/2/28 3:28:03 来源:https://blog.csdn.net/jianzhanyes/article/details/145890497  浏览:    关键词:wordpress按分类ID调用最新、推荐、随机内容

在WordPress中,可以通过自定义查询(WP_Query)来按分类ID调用最新、推荐(自定义字段或标签)、随机内容。以下是一些示例代码,帮助你实现这些功能。

1. 按分类ID调用最新内容

以下代码可以调用指定分类ID下的最新文章:

<?php
// 设置分类ID和文章数量
$category_id = 1; // 替换为你的分类ID
$posts_per_page = 5; // 显示的文章数量$args = array('post_type' => 'post', // 文章类型'posts_per_page' => $posts_per_page, // 每页显示的文章数量'orderby' => 'date', // 按日期排序'order' => 'DESC', // 降序排列(最新文章在前)'cat' => $category_id // 指定分类ID
);$query = new WP_Query($args);if ($query->have_posts()) {while ($query->have_posts()) {$query->the_post();?><div class="post-item"><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3><p><?php the_excerpt(); ?></p></div><?php}
} else {echo '<p>没有找到文章。</p>';
}wp_reset_postdata(); // 重置查询
?>

2. 按分类ID调用推荐内容

推荐内容可以通过自定义字段或标签实现。假设你使用自定义字段is_recommended来标记推荐文章(值为true或1):

<?php
$category_id = 1; // 替换为你的分类ID
$posts_per_page = 5; // 显示的文章数量$args = array('post_type' => 'post','posts_per_page' => $posts_per_page,'orderby' => 'date', // 按日期排序'order' => 'DESC', // 降序排列'cat' => $category_id,'meta_query' => array( // 自定义字段查询array('key' => 'is_recommended', // 自定义字段名称'value' => 'true', // 自定义字段值'compare' => '='))
);$query = new WP_Query($args);if ($query->have_posts()) {while ($query->have_posts()) {$query->the_post();?><div class="post-item"><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3><p><?php the_excerpt(); ?></p></div><?php}
} else {echo '<p>没有找到推荐文章。</p>';
}wp_reset_postdata(); // 重置查询
?>

调用随机内容

以下代码可以调用指定分类ID下的随机文章:

<?php
$category_id = 1; // 替换为你的分类ID
$posts_per_page = 5; // 显示的文章数量$args = array('post_type' => 'post','posts_per_page' => $posts_per_page,'orderby' => 'rand', // 随机排序'cat' => $category_id
);$query = new WP_Query($args);if ($query->have_posts()) {while ($query->have_posts()) {$query->the_post();?><div class="post-item"><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3><p><?php the_excerpt(); ?></p></div><?php}
} else {echo '<p>没有找到文章。</p>';
}wp_reset_postdata(); // 重置查询
?>

 原文

http://www.dulizhan.sd.cn/jianzhan/139.html

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词