2017-07-13 209 views
0

我喜欢在第一页的主页上发布帖子,仅在某个类别发布帖子,当用户点击下一页时,他会看到其他所有内容。Wordpress在第一页显示某个类别的帖子

我将此添加到我的functions.php:

function my_home_category ($query) { 
    if ($query->is_home() && !($query->is_paged()) && $query->is_main_query()) { 
    $query->set('cat', '2'); 
    } 
} 
add_action ('pre_get_posts', 'my_home_category'); 

和它的作品。唯一的问题是,当我去page 2时,我看到的帖子通常会在第2页(如果我没有这个功能),而不是所有类别的最新帖子。因此,如果以前在第一页上有其他类别的帖子,我现在无法在任何地方看到它们。

所以该功能之前,我的博客是这样的:

Page1: A, B, C, B, A <br> 
Page2: B, A, A, C, B <br> 

(A指从A类的帖子...)

,我想有这样的:

Page1: B, B, B, B, B <br> 
Page2: A, C, A, A, A <br> 
Page3: C ... <br> 

但是发生了什么是:

Page1: B, B, B, B, B <br> 
Page2: B, A, A, C, B <br> 

你能帮助我吗?

回答

0

修改你的函数的东西:

function my_home_category ($query) { 
    if ($query->is_home() && !($query->is_paged()) && $query->is_main_query()) { 
    $query->set('cat', '2'); 
    } 
    else{ 
     //Manually determine page query offset (offset + current page (minus one) x posts per page) 
     $page_offset = $offset + (($query->query_vars['paged']-1) * $ppp); 
     //Apply adjust page offset 
     $query->set('offset', $page_offset); 
    } 
} 
add_action ('pre_get_posts', 'my_home_category'); 
+0

谢谢,经过小编辑这个作品。 Hovewer不像我想要的那样。现在发生的是:Page1:B,B,B,B,B第2页:A,B,C,B,A(B类别的帖子再次出现)。 – JiriNovak

+0

此外,博客的最后一页会消失。博客上的页面数量仍然相同,但由于它是从第2页开始的,因此最后一个页面现在缺失。 – JiriNovak

+0

在'else'内加入条件: /*在$ do_not_duplicate */ 设置第一页ID $'query-> set('post__not_in',$ do_not_duplicate);' – amit

0

我想修改我index.php来解决重复问题上面:

<?php if (have_posts()) : ?> 

     <?php while (have_posts()) : the_post(); 
     $post_id = get_the_ID(); 
     if (in_array($post_id, $do_not_duplicate)) { 
      continue; // We've already seen this post ID, so skip the rest of the loop 
     } 

     $do_not_duplicate[] = $post_id; 
     ?> 
.... the content of post ... 

但这没有帮助。

相关问题