How to get an array of years from all of the search results, and use it to filter by year the paginated loop?


I hope this is not too dumb: even though I’m learning at an acceptable rate, my WP knowledge still has some important gaps.

What do I have:

My search.php template gets its results from the normal global $wp_query; $wp_query -> found_posts correctly returns the whole amount of results (say, 132) and $wp_query -> post_count, being the loop paginated, returns the correct number of posts fot that page up to the maximum of posts_per_page (say, 10).

What do I need:

I’m trying to put a filter by year <select> at the bottom of the page; of course it should allow the user to pick from the years from ALL of the 132 results and not only by the 10 in the current page.

What does trouble me:

$wp_query -> posts only holds the post_count posts pertinent to the current page, not all of the 132. If I alter the search query via a pre_get_posts filter, telling her to set posts_per_page to -1 when is_search(), of course I get all the 132 posts, but also I lose pagination.

What did I come up to so far:

I thought I’d need a “whole” query, parallel to $wp_query, holding up all of its potential results, not only the LIMITed ones.
So how do I populate this elusive array of years?

  1. Just to be sure to get from the very same bunch of results of $wp_query, I assign $wp_query -> request, but without its LIMIT clause, to a variable; then I $wpdb -> get_results it;
  2. I pick the year from each result and I put it into the array;
  3. I array_unique the array.


I’m pretty sure there must be a better, shorter, more efficient and maybe even “WP core”ish way to to this; but I haven’t been able to get to it so far, nor to find an answer here or elsewhere.

Could any of you route me to the right direction?


, , , Marks 3 years 2020-07-06T13:11:48-05:00 0 Answers 70 views 0

Leave an answer