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

问题描述 投票:0回答:1

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

这可能吗?

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

php wordpress
1个回答
0
投票

试试这个(尽管代码未经测试)。

$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' );
}
© www.soinside.com 2019 - 2024. All rights reserved.