0

I'm trying to create a custom page for a WordPress theme, which is a child theme of the Twenty Twenty theme. I'm simply trying to use WP_Query() to filter out posts so that it only displays posts with the category slug locations, however it produces two issues.

1.) It does not filter out the posts, and shows posts in any category.

2.) The error Notice:

Undefined offset: 9 in /Users/g/Documents/MAMP/childtheme/wp-includes/class-wp-query.php on line 3271 repeats over and over with increasing offsets numbers until the browser crashes.

$q = new WP_Query( array('category_name' => 'locations' ));

if ( $q->have_posts() ) {

    while ( $q->have_posts() ) {

        the_post();
        get_template_part( 'template-parts/content', get_post_type() );

    }
} 

I have a feeling it's something silly, but I have been at it for a few hours and haven't found the issue. Any help would be appreciated.

1
  • You need only the function the_post(); to map to your custom loop $q, like $q->the_post(); and the filter should run.
    – bueltge
    Jun 10, 2020 at 6:08

1 Answer 1

0

the_post() operates on the main query, but this isn't the main query you're looping over, you need to use $q->the_post()

Remember:

  • the_post() is the same as global $wp_query; $wp_query->the_post();
  • All post loops are WP_Query post loops if you dig down deep enough, even get_posts has a WP_Query inside it
  • There can only be 1 current post in $post, calling the_post sets that global variable.

This is what a standard post loop should look like:

$args = [
    // parameters go here
];
$query = new WP_Query( $args );
if ( $query->have_posts() ) { 
    while ( $query->have_posts() ) {
        $query->the_post();
        // display the post
        the_title();
        the_content();
    }
    wp_reset_postdata();
} else {
    esc_html_e( 'no posts were found', 'textdomain' );
}
2
  • That worked! Thanks. But I'm still a bit confused as to why. I'm assuming $q->have_posts() is pulling only posts that register "true" with the WP_Query Parameters (category_name = "locations"), so is it that once it registers true, it needs $q->the_post() in order to tell wordpress to show posts that meets these parameters?
    – Mei
    Jun 9, 2020 at 20:13
  • the_post always sets the current post from the main query. $q is not the main query. Remember the_post()` is the same as global $wp_query; $wp_query->the_post();
    – Tom J Nowell
    Jun 9, 2020 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.