如果不使用SQL,我想不出一种方法可以在一个查询中获得最新的5篇文章和一篇特定的文章。
如果您不介意使用两个查询,我认为这将是一种简单的方法来实现您的目标:
//Get the latest 5 posts (which happens to be get_posts default \'posts_per_page\' value)
$posts = get_posts();
//Build up an array with the IDs
$latests_posts_ids = wp_list_pluck( $posts, \'ID\' );
//Insert the desired ID in the third position
$post_id_to_insert = 1;
$insert_position = 2; //which equals 3 when starting from 0
array_splice( $latests_posts_ids, $insert_position, 0, $post_id_to_insert );
//Get the posts based on the IDs and do not alter their order
$args = array(
\'posts_per_page\' => 6,
\'post__in\' => $latests_posts_ids,
\'orderby\' => \'post__in\'
);
$posts = get_posts( $args );
//Parse the posts
foreach( $posts as $post ) :
setup_postdata( $post );
the_title();
endforeach;
我正在使用
get_posts()
但您可以安全使用
WP_query 相反
WordPress已在中处理可能的重复项post__in
, 如果你想插入的帖子是最新的5篇文章之一,情况就是这样。