Reputation: 45
For some reason I need query posts twice in archive page, they need different page limitation.
for example, the first query need show 10 posts which have some custom fields. The second query need show 20 posts which have different custom fields.
it looks OK, but when I add 'showposts=10' for the second query, it looks show the posts but not belong to current category.
<?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();?>
Upvotes: 0
Views: 493
Reputation: 5639
So what you need here is get_queried_object
Function Get Queried Object to pull the current category id, then do your loops using the WP_Query
class rather than get_posts
. From what is below, you should be able to modify this to suit your needs.
$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();
Upvotes: 2