Forums › Forums › Search & Filter Pro › Restrict results to date range
- This topic has 26 replies, 2 voices, and was last updated 10 years, 4 months ago by Ross.
-
Anonymous(Private) June 18, 2014 at 11:54 am #1677
Hi Ross,
my (custom) posts feature deals and offers, and these have an expiry date. I would like to only show search results which have not expired yet.
The expiry date field that’s already in each post as standard (not ACF) is being recognised by your plugin so that’s great. Any ideas on how I would do this?
Many thanks in advance,
Philip.Ross Moderator(Private) June 18, 2014 at 12:34 pm #1679Hey Philip
Add this code to the bottom your functions.php file in your theme
add_action( 'pre_get_posts', 'filter_post_dates' ); function filter_post_dates($query) { //this function changes the order of your posts by date if ( !is_admin() && $query->is_main_query() ) { $query->set( 'order', 'ASC' ); //a $query->set( 'orderby', 'date' ); add_filter( 'posts_where', 'after_date_filter'); } return $query; } function after_date_filter( $where = '' ) { //here we limit the results to only the posts set in from today onwards: $today = date( 'Y-m-d' ); $where .= " AND post_date >= '$today'"; return $where; remove_filter( 'posts_where', 'after_date_filter'); }
There is one thing though, I think that posts published in the future (ie with post date) are not considered
published
by wordpress so they not display.. but I guess you already know that… In this case you may have to use the custom field, which means the code above will need to be different (let me know and I’ll look)…Just to note, your results page (once you submit the search form) does not match the layout of your initial search page… let me know if you need help with that I have some recommendations on the best way to set it up.
Thanks
Ross Moderator(Private) June 18, 2014 at 1:03 pm #1681Hey Philip, sorry I’m a bit confused, is the code working? I just realised that this code would apply to all queries on your site, and not just S&F, so I would update it with this:
add_action( 'pre_get_posts', 'filter_post_dates', 21 ); function filter_post_dates($query) { global $sf_form_data; if ( !is_admin() && $query->is_main_query() && $sf_form_data->is_valid_form() ) { $query->set( 'order', 'ASC' ); $query->set( 'orderby', 'date' ); add_filter( 'posts_where', 'after_date_filter'); } return $query; } function after_date_filter( $where = '' ) { $today = date( 'Y-m-d' ); $where .= " AND post_date <= '$today'"; return $where; remove_filter( 'posts_where', 'after_date_filter'); }
But just to note, this code only applies once you have pressed search once on your form (even if its blank)…
-
AuthorPosts