繁体   English   中英

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在当前帖子之后开始。 虽然不确定如何计算循环中当前帖子的索引。

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

$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. 第一次运行循环,以检查循环中当前帖子的索引
  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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM