博客 / WordPress/ WordPress如何调用最新/热门/指定分类文章

WordPress如何调用最新/热门/指定分类文章

获取数据是我们在开发一款WordPress主题时经常会用到的,随着主题功能越来越多、需求的多样性,调用文章的需求也变得多种多样,最常见应该是调用最新文章、调用热门文章、调用指定分类文章了。

今天带来一篇关于调用最新/热门/指定分类文章的WordPress教程,希望能对大家有所帮助。

调用指定分类文章

使用 query_posts 函数可以快速调用指定分类的文章。但请注意,query_posts 会修改主查询,可能影响页面其他部分,通常建议在侧边栏等次要循环中使用,或在主循环前使用 wp_reset_query() 重置。

<?php
// 调用分类ID为1的最新5篇文章
query_posts('cat=1&posts_per_page=5');
while (have_posts()) : the_post(); ?>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php endwhile;
wp_reset_query(); // 重置查询,避免影响后续主循环
?>

参数说明:

  • cat: 分类ID。
  • posts_per_page: 显示的文章数量(推荐使用此参数替代已废弃的 showposts)。

调用最新文章

调用最新文章是基础需求,可以指定分类,也可以不指定(调用全站最新文章)。

<?php
// 调用全站最新6篇文章
$args = array(
    'posts_per_page' => 6,
    'orderby' => 'date', // 按发布日期排序
    'order' => 'DESC' // 降序,最新的在前
);
$latest_posts = new WP_Query($args);
if ($latest_posts->have_posts()) :
    while ($latest_posts->have_posts()) : $latest_posts->the_post(); ?>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <?php endwhile;
    wp_reset_postdata(); // 重置文章数据
endif;
?>

说明: 使用 WP_Query 对象是更现代、更安全的方式,它不会干扰主查询。

调用热门文章

热门文章通常按评论数或浏览量排序。以下示例演示如何按评论数排序调用热门文章。

<?php
$post_num = 10; // 显示篇数
$args = array(
    'post_status' => 'publish', // 只选公开的文章
    'post__not_in' => array(get_the_ID()), // 排除当前文章(如果在文章页调用)
    'ignore_sticky_posts' => 1, // 忽略置顶文章(推荐使用此参数替代已废弃的 caller_get_posts)
    'orderby' => 'comment_count', // 依评论数排序
    'order' => 'DESC', // 降序,评论最多的在前
    'posts_per_page' => $post_num
);
$popular_posts = new WP_Query($args);
if ($popular_posts->have_posts()) :
    while ($popular_posts->have_posts()) : $popular_posts->the_post(); ?>
        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <?php endwhile;
    wp_reset_postdata();
endif;
?>

关键修正与说明:

  • 将已废弃的 caller_get_posts 参数更新为标准的 ignore_sticky_posts => 1
  • 使用 get_the_ID() 动态获取当前文章ID,使代码更通用。
  • 使用 WP_Query 对象和 wp_reset_postdata() 是处理自定义查询的最佳实践。
  • 如需按浏览量排序,通常需要借助如“WP-PostViews”这类插件,或自定义字段来实现,orderby 参数需相应调整。

以上方法均提供了清晰的代码示例和参数解释,你可以根据实际需求调整参数,灵活地调用所需的文章列表。

发表评论

您的邮箱不会公开。必填项已用 * 标注。