首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在WordPress循环中首先显示特定类别的帖子

在WordPress循环中首先显示特定类别的帖子
EN

Stack Overflow用户
提问于 2018-08-17 07:02:24
回答 1查看 285关注 0票数 0

我想首先在主页中显示某个类别的帖子,然后继续默认的WordPress帖子顺序。

这有可能吗?

我已经尝试使用两个循环,并使用我想要的类别过滤第一个循环,但是我认为分页不会像预期的那样工作。

EN

回答 1

Stack Overflow用户

发布于 2018-08-17 07:20:56

试试这个(不过是未测试的代码)。

代码语言:javascript
复制
$total_posts_to_display = 10; // Change accordingly

$id_of_category_1 = 4; // Change accordingly

$filtered_posts = array(); // Array to be filled in with all posts, ordered by "category 1" first

$posts_in_category_1 = get_posts( array(
    'numberposts' => $total_posts_to_display,
    'category'    => $id_of_category_1
) );

$ramaining_posts_number = $total_posts_to_display - count( $posts_in_category_1 );

if ( $ramaining_posts_number > 1 ) {
   $excluded_post_ids = array();
   foreach( $posts_in_category_1 as $ep ) {
       array_push( $excluded_post_ids, $ep->ID );
   }
   $remaining_posts = get_posts( array(
       'numberposts' => $ramaining_posts_number,
       'exclude'     => $excluded_post_ids
   ) );
} else {
   $remaining_posts = array();
}

$filtered_posts = array_merge( $posts_in_category_1, $remaining_posts );

我还有一个更复杂的解决方案,可以支持分页!您需要将其放在functions.php

代码语言:javascript
复制
add_action( 'pre_get_posts', 'my_custom_home_post_ordering' );

function my_custom_home_post_ordering( $query ) {
    if ( ! is_home() ) {
        return;
    }
    if ( ! $query->is_main_query() ) {
        return;
    }
    $posts_in_category_1 = get_posts( array(
        'posts_per_page' => -1,
        'category'       => 4 // Change accordingly. You may also use 'category_name', instead.
        'fields'         => 'ids'
    ) );
    $query->set( 'post__in', $posts_in_category_1 );
    $query->set( 'orderby', 'post__in' );
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51886393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档