如何从WordPress分类页面获取前两篇文章的ID?
在WordPress分类/标签页面获取前两篇文章ID
方法一:复用当前页面的主循环
分类/标签页面本身已经加载了对应的文章列表主循环,直接在循环里捕获前两个ID即可,不会额外增加数据库查询:
$first_two_post_ids = array(); if ( have_posts() ) { $count = 0; // 只循环前两篇文章 while ( have_posts() && $count < 2 ) { the_post(); $first_two_post_ids[] = get_the_ID(); $count++; } // 重置循环指针,保证后续文章列表正常输出 rewind_posts(); } // 后续可直接使用$first_two_post_ids数组,比如打印测试: // print_r($first_two_post_ids);
方法二:单独发起查询(适合主循环外的场景)
如果需要在侧边栏、页眉等主循环之外的位置获取ID,可以用WP_Query单独查询,动态匹配当前分类/标签:
// 获取当前页面对应的分类/标签对象 $current_term = get_queried_object(); // 构建查询参数 $args = array( 'post_type' => 'post', 'posts_per_page' => 2, 'tax_query' => array( array( 'taxonomy' => $current_term->taxonomy, 'field' => 'term_id', 'terms' => $current_term->term_id, ), ), 'no_found_rows' => true, // 关闭计数查询,优化性能 ); $query = new WP_Query( $args ); $first_two_post_ids = array(); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $first_two_post_ids[] = get_the_ID(); } // 重置全局文章对象,避免干扰其他内容 wp_reset_postdata(); } // 使用ID数组 // print_r($first_two_post_ids);
内容的提问来源于stack exchange,提问作者Pawel Pluto
相关产品推荐
相关产品推荐

