【问题标题】:Wordpress show posts from certain category on first pageWordpress 在第一页显示特定类别的帖子
【发布时间】:2017-07-13 06:27:58
【问题描述】:

我喜欢在首页上只显示特定类别的帖子,当用户点击下一页时,他会看到其他所有内容。

我将此添加到我的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>

你能帮帮我吗?

【问题讨论】:

    标签: php wordpress loops


    【解决方案1】:

    将你的函数修改为:

    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');
    

    【讨论】:

    • 谢谢,经过少量编辑后,这工作。然而并不完全如我所愿。现在发生的是:第1页:B、B、B、B、B第2页:A、B、C、B、A(B类的帖子又出现了)。
    • 另外,博客的最后一页消失了。博客上仍然有相同数量的页面,但由于它是从第 2 页开始的,所以现在缺少最后一个。
    • else 内添加条件:/*在$do_not_duplicate 中设置首页ID */ $query-&gt;set('post__not_in', $do_not_duplicate);
    • 你能告诉我完整的代码吗?还有什么放在 index.php 上?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多