您需要进行初始提取,查看您获得了多少结果,然后“随机”获得一些您缺少总数的帖子,对它们进行标记,然后根据基准元值对它们进行排序。循环集是不同的,因为它使用get_posts()
而不是WP_Query
使它更容易作为数组使用。
请注意,我没有运行下面的代码,这是一个概念证明并且未经测试
// The total posts to display
$total_count = 3;
// The query args
$args = array(
'post_type' => 'koncert',
'posts_per_page' => $total_count,
'meta_query' => array(
array(
'key' => 'featured', // name of custom field
'value' => '1',
'compare' => '='
),
),
'meta_key' => 'datum',
'orderby' => 'meta_value',
'order' => ASC
);
// Get the posts that are "featured"
$featured = get_posts( $args );
// Figure out if we need to fetch "random" posts to get to the $total_count
$rnd_count = $total_count - count( $featured );
if ( $rnd_count > 0 ) {
// Make sure we don't get the same posts
$post__not_in = array();
for ( $featured as $f ){
$post__not_in[] = $f->ID;
}
// Set up the args for a random post
$args = array(
'post_type' => 'koncert',
'posts_per_page' => $rnd_count,
'post__not_in' => $post__not_in,
'orderby' => 'rand', // http://codex.wordpress.org/Template_Tags/get_posts#Random_posts
);
// Get the "random" posts now that we remove the meta filter and excluding the ones we already fetched
$random = get_posts( $args );
// Merge into a single array
$featured = array_merge( $featured, $random );
// Get the datum meta for each post so we can sort on it
$sort = array();
$post_by_id = array();
for ( $featured as $f ){
$sort[ $f->ID ] = get_post_meta( $f->ID, 'datum', true );
$post_by_id[ $f->ID ] = $f;
}
// Sort and maintain key since it's the post
asort( $sort, SORT_STRING ); // use SORT_NUMERIC for numbers, see http://www.php.net/manual/en/function.sort.php
$i = 0;
for ( $sort as $key => $s ){
$featured[$i++] = $post_by_id[ $key ];
}
}
// since we used get_posts() and not WP_Query, use the following to create the loop.
for ( $featured as $f ){
global $post;
$post = $f;
setup_postdata( $post );
// use the_content() etc
}