我有两种自定义帖子类型,希望在同一个查询中显示其中一种按标题排序,另一种在随机位置显示。
So CPT A(排序)en CPT B(随机):
A1 A2 A3B2 A4 A5B5 A6 A7 A8 A9B1 ...
或A1B1 A2 A3B5 A4 A5 A6 A7 A8 A9B7 ...
或
B4 A1 A2 A3 A4B3 A5 A6 A7 A8B1 A9。。。
我尝试合并两个CPT,但没有按预期效果。
$projectposts = get_posts(array(
\'posts_per_page\' => -1,
\'post_type\' => \'project\',
\'order\' => \'ASC\'
));
//second query
$storieposts = get_posts(array(
\'posts_per_page\' => -1,
\'post_type\' => \'storie\',
\'order\' => \'rand\'
));
$mergedposts = array_merge( $projectposts, $storieposts ); //combined querie
@kero:
我有这个↓ 它几乎起作用了。。。看起来这会在数组中创建一些空条目。(我百分之百确定在合并之前没有空标题。)
查询结果为A3 A2 A4 A6 B2(空)(空)(空)A1(空)(空)B1 B3。。。
$projectposts = get_posts([
\'posts_per_page\' => -1,
\'post_type\' => \'project\',
\'order\' => \'ASC\',
\'meta_query\' => array(
array(
\'key\' => \'featured\',
\'value\' => \'"homepagina"\',
\'compare\' => \'LIKE\'
)
)
]);
$storieposts = get_posts([
\'posts_per_page\' => -1,
\'post_type\' => \'story\',
\'order\' => \'ASC\',// not rand!
\'meta_query\' => array(
array(
\'key\' => \'featured\',
\'value\' => \'"homepagina"\',
\'compare\' => \'LIKE\'
)
)
]);
function array_random_merge(array $a, array $b): array {
while (count($b) > 0) {
shuffle($b);
// get one entry of $b
$item = array_shift($b);
// find random position inside $a
$pos = mt_rand(0, count($a) - 1);
// insert $item into $a
array_splice($a, $pos, 0, $item);
}
return $a;
}
$mergedposts = array_random_merge($projectposts, $storieposts);
if( $mergedposts ) {
foreach( $mergedposts as $post ) {
echo \'<h3>\';
echo the_title();
echo \'</h3>\';
}
}
wp_reset_postdata();