我使用两个循环查询:
<?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'
发布于 2019-02-20 00:27:57
Wordpress文档建议您应该尽可能避免使用帖子声明:
注意:此函数将完全覆盖主查询,不适合插件或主题使用。它过于简单的修改主查询的方法可能会有问题,应该尽可能避免。
相反,我们可以使用查询。我们将使用第一个循环来存储post 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() arguments
'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,如果您正在运行多个查询,它值得一看。
祝你的项目好运!
https://stackoverflow.com/questions/54773191
复制相似问题