出于某种原因,我需要在归档页面中发布两次查询文章,它们需要不同的页面限制。
例如,第一个查询需要显示10个具有一些自定义字段的帖子。第二个查询需要显示20个具有不同自定义字段的帖子。
它看起来不错,但是当我在第二个查询中添加'showposts=10‘时,它看起来显示的是帖子,但不属于当前类别。
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_field('custom-fields-1'); ?>
<?php endwhile; ?>
<?php else : ?>
<h3>Not Found</h3>
<?php endif; ?>
<?php wp_reset_query();?>
<?php query_posts('showposts=10'); if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_field('custom-fields-2'); ?>
<?php endwhile; ?>
<?php else : ?>
<h3>Not Found</h3>
<?php endif; ?>
<?php wp_reset_query();?>发布于 2020-04-05 11:19:21
因此,这里需要的是get_queried_object 函数获取查询对象来提取当前的类别id,然后使用WP_Query类而不是get_posts来执行循环。从下面的内容来看,您应该能够修改它以满足您的需要。
$catObject = get_queried_object();
$category = $catObject->term_id;
// WP_Query arguments for first loop
$args = array(
'posts_per_page' => '10',
'tax_query' => array(
array(
'taxonomy' => 'category',
'terms' => $category,
),
),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'custom_field_1',
'compare' => 'EXISTS',
),
),
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
// Do your stuff with the first loop
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
// WP_Query arguments for second loop
$args2 = array(
'posts_per_page' => '10',
'tax_query' => array(
array(
'taxonomy' => 'category',
'terms' => $category,
),
),
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'custom_field_2',
'compare' => 'EXISTS',
),
),
);
// The Query
$query2 = new WP_Query( $args2 );
// The Loop
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
// Do your stuff with the second loop
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();https://stackoverflow.com/questions/61036732
复制相似问题