我正在使用两个循环查询:
<?php
// show all coupons marked Top Coupon
query_posts(array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
'meta_key' => 'clpr_topcoupon',
'meta_value'=> 1,
APP_TAX_STORE => $term->slug,
'ignore_sticky_posts' => 1,
'posts_per_page' => 1
));
?>
<?php get_template_part( 'loop3', 'coupon' ); ?>
<?php
query_posts( array(
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
APP_TAX_STORE => $term->slug,
'ignore_sticky_posts' => 1,
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'clpr_excoupon',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'clpr_excoupon',
'compare' => '!=',
'value' => '1'
),
),
) );
?>
<?php get_template_part( 'loop1', 'coupon' ); ?>
现在,我不想在第二个循环中显示第一个循环中的第一个帖子。我尝试过get_the_ID();
,但是如果此人没有'meta_key' => 'clpr_topcoupon'
,则缺少一条信息。我如何从第一篇博文中获得get_the_ID();
,但前提是它只有'meta_key' => 'clpr_topcoupon'
?
答案 0 :(得分:0)
wordpress文档建议您尽可能避免使用query_posts:
注意:此功能将完全覆盖主查询,并且不适合插件或主题使用。它过于简单的修改主查询的方法可能会出现问题,应尽可能避免。
相反,我们可以使用WP_Query。我们将使用第一个循环来存储帖子ID,并在第二个循环中对其进行检查。也许是这样的:
<?php
//set parameters for First query
$args = array('post_type' => APP_POST_TYPE,
'post_status' => 'publish',
'meta_key' => 'clpr_topcoupon',
'meta_value'=> 1,
APP_TAX_STORE => $term->slug,
'ignore_sticky_posts' => 1,
'posts_per_page' => 1 );
$first_query = new WP_Query($args); // create query
$post_id = 0;
//initialize loop for custom query like this
if ($first_query->have_posts() ) {
while ($first_query->have_posts() ) {
$first_query->the_post();
$post_id = $post->ID; //store post ID outside of loop
get_template_part( 'loop3', 'coupon' );
}
}
wp_reset_postdata();
//setup second query
$args = array( //excludes post from query by ID See Bill erikson for complete list of WP_Query() arguements
'post__not_in' => array($post_id),
'post_type' => APP_POST_TYPE,
'post_status' => 'publish',
APP_TAX_STORE => $term->slug,
'ignore_sticky_posts' => 1,
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'clpr_excoupon',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'clpr_excoupon',
'compare' => '!=',
'value' => '1'
)
)
);
$second_query = new WP_Query($args);
if ($second_query->have_posts() ) {
while ($second_query->have_posts() {
$second_query->the_post();
get_template_part( 'loop1', 'coupon' );
}
}
wp_reset_postdata();
希望此代码能够为您提供帮助。如您所见,WP_Query接受参数'post__not_in',该参数采用页面ID的数组并将其从查询中排除。我们从第一个查询中检索了ID,并在第二个查询的参数中对其进行了引用。我还提供了wp_reset_postdata
,如果您正在运行多个查询,则值得一看。
祝您好运!