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.
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.
Share Improve this question edited Jun 10, 2020 at 6:07 bueltge 17.1k7 gold badges62 silver badges97 bronze badges asked Jun 9, 2020 at 19:21 MeiMei 32 bronze badges 1 |1 Answer
Reset to default 0the_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 asglobal $wp_query; $wp_query->the_post();
- All post loops are
WP_Query
post loops if you dig down deep enough, evenget_posts
has aWP_Query
inside it - There can only be 1 current post in
$post
, callingthe_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' );
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742360733a4429340.html
the_post();
to map to your custom loop$q
, like$q->the_post();
and the filter should run. – bueltge Commented Jun 10, 2020 at 6:08