我想合并以下两个查询,以便在其他促销(查询2)之前显示正在进行的促销(查询1),但总共显示的结果不超过5个。谢谢
查询#1正在进行的促销
<?php
global $post;
$args = array(
\'post_type\' => \'promotions\',
\'numberposts\' => 5,
\'meta_key\' => \'sp_ongoingPromotion\',
\'meta_value\' => 1
);
$supplierCommunications = get_posts( $args );
foreach( $supplierCommunications as $post ) : setup_postdata($post);
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><br/>
<span>
<?php
echo "Ongoing Promotion";
?>
</span>
</li>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
查询#2当前促销
<?php
global $post;
$args = array(
\'post_type\' => \'promotions\',
\'numberposts\' => 5,
\'meta_key\' => \'sp_endDate\',
\'meta_value\' => date("Y/m/d"),
\'meta_compare\' => \'>=\',
\'orderby\' => \'meta_value\',
\'order\' => \'ASC\'
);
$supplierCommunications = get_posts( $args );
foreach( $supplierCommunications as $post ) : setup_postdata($post);
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<br/>
<span>
<?php
$meta = get_post_meta(get_the_ID(), \'sp_endDate\', true);
if(\'\' != $meta) {
$formattedDate = new DateTime($meta);
echo "Expires: ".$formattedDate->format(\'F d, Y\');
}
?>
</span>
</li>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
最合适的回答,由SO网友:EAMann 整理而成
我不会组合这些查询,主要是因为它们键入的是不同的元键和值。WP查询API非常强大,但您正在尝试在这里执行一些非常高级的搜索和排序。
一种选择是手工编写原始SQL查询并将其传递到$wpdb->get_results()
, 但这不一定是未来安全的(即,如果将来的版本更改了DB模式)。
相反,我建议您分别执行这两个查询并合并这两个数组。
一些(非常粗糙的)伪代码:
// Get your promotions using the arguments you outlined above.
$ongoing_promotions = get_posts( $ongoing_args );
$current_promotions = get_posts( $current_args );
// Merge the two arrays
$all_promotions = array_merge( $ongoing_promotions, $current_promotions );
// Get just the IDs of your promotions
$promotion_ids = wp_list_pluck( $all_promotions, \'ID\' );
// Do a new query with these IDs to get a properly-sorted list of promotions
$promotions = get_posts( array(
\'post__in\' => $promotion_ids,
\'post_type\' => \'promotion\',
\'post_status\' => \'publish\'
) );
// Now loop through your promotions
foreach( $posts as $post ) :
setup_postdata($post); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<br/>
<span>
<?php
$meta = get_post_meta(get_the_ID(), \'sp_endDate\', true);
if ( \'\' != $meta ) {
$formattedDate = new DateTime( $meta );
echo "Expires: ".$formattedDate->format(\'F d, Y\');
}
?>
</span>
</li>
<?php endforeach; ?>