Wordpress WP_Query获取下一个帖子与同一类别


Wordpress WP_Query get next post with same category

我正试图获得与WP中当前帖子相同类别的下一个帖子。我不是想获得下一篇文章的链接(next_post_link()),而是文章本身。

目前我只得到相同类别的最新帖子,这不是帖子本身。

$query = new WP_Query( array( 'category_name' => $maincat_slug, 'posts_per_page' => 1, 'post__not_in' => array( $post->ID )) );
if ( $query->have_posts() ) : 
    while ( $query->have_posts() ) : $query->the_post(); 
        get_template_part( 'template-parts/content', 'teaser' ); 
    endwhile;
endif;

$maincat_slug包含当前岗位(get_the_category())的(第一)类段塞。

也许我们可以改变'post__not_in'包括当前和所有以前的帖子?

编辑:

get_next_post_link没有类别过滤器,所以我认为这在这里不起作用。

或者我们可以使用offset在当前帖子之后开始。不知道如何计算循环内的当前帖子的索引。

这就是我如何使用wp_query offset

  1. 第一次运行循环,检查循环中当前帖子的Index
  2. 设置第二个循环的偏移量为当前页的索引(+1)
  3. 以第一个循环的偏移量运行第二个循环。

这样,第二个循环忽略当前帖子之前的所有帖子,并显示当前帖子之后的第一个帖子。

代码:

// Get current category (first cat if multiple are set)
$category = get_the_category(); 
$maincat_slug = $category[0]->slug;
// Get current Post ID
$current_id = $post->ID; 
// Reset offset
$offset = 0;
// Calculate offset
$query = new WP_Query( array( 'category_name' => $maincat_slug ) );
if ( $query->have_posts() ) : 
    while ( $query->have_posts() ) : 
        $query->the_post(); 
        $test_id = $post->ID;
        if ( $test_id == $current_id ) :
            // Set offset to current post
            $offset = $query->current_post + 1;
        endif;
    endwhile; 
endif;
// Display next post in category
$query = new WP_Query( array( 'category_name' => $maincat_slug, 'posts_per_page' => 1, 'offset' => $offset) );
if ( $query->have_posts() ) : 
    while ( $query->have_posts() ) : 
        $query->the_post(); 
        get_template_part( 'template-parts/content', 'teaser' ); 
    endwhile; 
else :
    // Fallback 
endif;

您可以使用url_to_postid()函数从链接中检索id,然后获取post:

$link = next_post_link();
$postid = url_to_postid( $link );
$query = new WP_Query( array( 'category_name' => $maincat_slug, 'posts_per_page' => 1, 'p' => $postid );
if ( $query->have_posts() ) : 
    while ( $query->have_posts() ) : $query->the_post(); 
        get_template_part( 'template-parts/content', 'teaser' ); 
    endwhile;
endif;