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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (38)

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

它甚至可能吗?

我已经尝试使用2个循环并使用我想要的类别过滤第一个循环但是我不认为分页将按预期工作。

提问于
用户回答回答于

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

$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

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

扫码关注云+社区

领取腾讯云代金券