WordPress Query Results: Using the date_query to Change the Query
Adjusting the query on a WordPress page should be done with caution. In this example, we’ll be adjusting it using the “pre_get_posts” hook in WordPress. If you’re unsure if this is the hook for you, double-check the documentation.
The “pre_get_posts” hook will allow us to adjust the query itself before it gets the posts because we only want to return posts after a certain date.
Also in my example, I set up the blog post page to not return any posts older than January 1, 2016, BUT I wanted to keep those posts live on the website. If we removed those posts, we’d need to forward all of them to other posts. As it was, the client wanted the posts still published, but not shown when users browse the blog page.
function wfc_modify( $query ) { if ( $query->is_main_query() && !is_single() ) { $wfc_date_query = array( array( 'after' => 'January 1, 2016', 'inclusive' => true, ), ); $query->set( 'date_query', $wfc_date_query ); return $query; } } // Hook add_action( 'pre_get_posts', 'wfc_modify' );
We have one action (bottom line above) that tells the “pre_get_post” hook to call the function “wfc_modify”.
Within the function, you’ll need to be a little careful. We check if it’s the main query (line 2) so if there are other queries going on, we don’t mess with them. Also, I don’t run it if we’re on a single post. Otherwise, the individual post would return a 404 page.
Using a date_query, we use a nested array (line 3 & 4) to indicate we only want posts after January 1, 2016. We could also add in a “before” option:
'after' => 'January 1, 2016', 'before' => 'Februrary 1, 2020',
The inclusive (line 6) item refers to whether the date itself is included in the results. If a post was published on January 1, 2016, it will be included.
Next, we set the “date_query” per our array “wfc_date_query” we created above.
Finally, we return the query. If don’t do this, you won’t see any results!
What We’ve Accomplished & the Downsides
We’ve removed the older posts from the primary blog page, while leaving the individual posts still live.
I wouldn’t recommend this for most sites, as Google doesn’t like “orphan” pages or posts. However, in specific instances, this might be the best choice for what you’re trying to accomplish. While you could completely remove the posts, that leaves you with 404s or you’ll need to forward all those posts to newer ones.