Wordpress WP_Query 获取下一个 post 相同类别

Wordpress WP_Query get next post with same category

我正在尝试在 WP 中获取与当前 post 具有相同类别的下一个 post。我不是要获取下一个 post (next_post_link()) 的 link,而是 post 本身。

目前我只获得相同类别的最新 post,而不是 post 本身。

$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 包括当前 post (get_the_category()) 的(第一个)类别 slug。

也许我们可以更改 'post__not_in' 以包括当前和所有以前的 post?

编辑:

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

或者我们可以用offset在当前post之后开始。不确定如何计算循环内当前 post 的索引。

您可以使用函数 url_to_postid() 从 link 中检索 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;

这就是我使用 wp_query offset

完成它的方法
  1. 运行循环第一次查看循环中当前post的Index
  2. 将第二个循环的偏移量设置为当前页面的索引 (+1)
  3. 运行 第二个循环与第一个循环的偏移量。

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

代码:

// 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;