最佳实践?在查询中引用帖子


best practice? referencing posts within queries

我正在尝试提取两个元值为 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();

1 - 所以要解决这个问题,你想通过使用"showposts"=> 2从你的"args1_query"中获取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 - 利润 ?