我想首先在首页中显示某个类别的帖子,然后继续WordPress帖子的默认顺序。
有可能吗?
我尝试使用2个循环,并用我想要的类别过滤第一个循环,但是我认为分页不会按预期工作。
答案 0 :(得分: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' );
}