Avoid using query_posts()
Please don’t use
query_posts('posts_per_page=10');
in your date.php
template file as it will override the main query instance and thus affect the main loop. This can truly ruin the day!
If you need to modify e.g. the posts_per_page
for the main date query, use the pre_get_posts
action to modify the query variables, before the database request is made.
There’s a harsh warning on query_posts()
usage in the manual.
So remove that part toghether with wp_reset_query()
and it should work again!
Yearly Date Archive: Modifying the number of posts
Here’s an example how to change the posts per page for the yearly date archive:
add_action( 'pre_get_posts', function( $query ) {
if ( is_admin() || ! $query->is_main_query() || ! $query->is_year() ) {
return;
}
$query->set( 'posts_per_page', 10 ); // Adjust the number to your needs!
} );
Here we use the is_year()
to target the yearly archive queries and the is_main_query()
to target only main queries.
Yearly Date Archive: Supporting the date-year.php
template file.
We can also add a support for the date-year.php
template file, by modifying the template filter example from the manual:
/**
* Add a support for date-year.php template files.
*/
add_filter( 'date_template', function( $templates ) {
if ( ! is_year() ) {
return $templates;
}
if ( ! is_array( $templates ) && ! empty( $templates ) ) {
$templates = locate_template( [ "date-year.php", $templates ], false );
} elseif ( empty( $templates ) ) {
$templates = locate_template( "date-year.php", false );
} else {
$new_template = locate_template( [ "date-year.php" ] );
if ( ! empty( $new_template ) ) {
array_unshift( $templates, $new_template );
}
}
return $templates;
} );
That way we are only working with the yearly date archive and not the others, like month and day if using the date.php
template file.
Note
Add the code snippets into your functions.php
file in the current theme directory or create a plugin. Never copy/paste some code snippets from the internet directly to a live site. Always test first on dev/local installs.