我试图将两个随机发布的元数据1和一个随机发布的元数据为2,并将其排列为循环:121
下面的脚本运行正常。但是,我相信它可以更有效地执行。从理论上讲,该函数也可以为args1a和args1b查询提供相同的帖子。
是否有某种方式可以引用args1的第一个和第二个结果(如果我要做showposts => 2)然后在新查询中调用它们?这样我可以避免对基本相同的参数进行两次单独的查询。
$args1a = array(
'meta_key' => 'key',
'meta_value' => '1',
'orderby' => 'rand',
'showposts' => 1,
);
$args1b = array(
'meta_key' => 'key',
'meta_value' => '1',
'orderby' => 'rand',
'showposts' => 1,
);
$args2 = array(
'meta_key' => 'key',
'meta_value' => '2',
'orderby' => 'rand',
'showposts' => 1,
);
$args1a_query = new WP_Query( $args1a );
$args1b_query = new WP_Query( $args1b );
$args2_query = new WP_Query( $args2 );
$loop = new WP_Query();
$loop->posts = array_merge( $args1a_query->posts, $args2_query->posts, $args1b_query->posts);
$loop->post_count = count( $loop->posts );
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
编辑:这是使用ROunofF解决方案完成的最终工作代码(编辑出一些错误)
$args1a = array(
'meta_key' => 'key',
'meta_value' => '1',
'orderby' => 'rand',
'showposts' => 2,
);
$args2 = array(
'meta_key' => 'key',
'meta_value' => '2',
'orderby' => 'rand',
'showposts' => 1,
);
$args1_query = new WP_Query( $args1 );
$args2_query = new WP_Query( $args2 );
$loop = new WP_Query();
$remainingPosts = array_splice($args1_query->posts, 1, 1, $args2_query->posts);
$loop->posts = array_merge($args1_query->posts, $remainingPosts);
$loop->post_count = count( $loop->posts );
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
答案 0 :(得分:0)
1 - 所以要解决这个问题,你想从你的" args1_query"中获得2个帖子。使用' showposts' => 2。
2 - 然后只需用下面的代码替换你的array_merge(评论中解释的步骤):
// Initially
// $args1_query->posts = [1a, 1b]
// $args2_query->posts = [2a]
$remainingPost = array_splice($args1_query->posts, 1, 1, $args2_query->posts);
// After splice (offset: 1, length: 1; so we replaced 1b by the content of args2_query_posts):
// $args1_query->posts = [1a, 2a]
// $remainingPost = [1b]
$loop->posts = array_merge($args1_query->posts, $remainingPosts);
// After merge
// $loop_posts = [1a, 2a, 1b]
splice方法允许用另一个数组替换数组的某些内容(提取)并返回提取的内容。
3 - 利润?