- I have a page template, call it page-myblog.php, that I want to display an ordinary loop on.
- I have created a page 'myblog' in the admin area and it crops up as normal on the front end.
- I want to show all my blog posts in the loop on that page template. I refuse to instantiate a new WP_Query on the page and I want to edit the main query instead.
This appraoch has not worked thanks to the following behaviour:
add_action( 'pre_get_posts', function( $query ) {
if( $query->query['pagename'] === 'myblog' ) {
$query->set( 'pagename', null );
$query->set( 'post_type', 'post' );
}
});
results in the following SQL being generated.
SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' ORDER BY wp_posts.post_date DESC
This query works, which is to say, it does find posts if you run it in an SQL console, but because it doesn't explicitly select IDs (I think?) there's nothing in my $query->posts array.
Why does this happen? And can I fix it?
wp_admin->Settings->Reading
and pick this page as the "Posts Page"?