wordpress - Wordpress 两个循环排除帖子
问题描述
我正在使用两个循环查询:
<?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'
?
解决方案
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() 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
了值得一看的内容。
祝你的项目好运!
推荐阅读
- highcharts - 绘制布尔值时使用 max yAxis
- c# - 如何调试导致 this.Close() 在表单加载时挂起的包装类问题?
- php - in_array 函数是阻止代码注入/sql 注入的安全方法吗?
- sql - 将结果减少到仅基于单个字段具有超过 1 个唯一行的结果
- java - 使用 Java 14 发布 Gluon 移动应用程序
- sql - oracle sql中的空间数据-两点之间的距离
- spring-boot - 大写时无法获取 xmlelements 的值
- python - 为什么我不能通过 BeautifulSoup 抓取亚马逊产品?
- php - 使用 Blogger API 和 PHP 设置描述、草稿和永久链接
- javascript - Javascript for loop 在计算 LCM 时给出无限循环错误