Home › Forums › Product Support Forums › Ajax Search Pro for WordPress Support › Show/hide results based on a datetime metafield
- This topic has 5 replies, 2 voices, and was last updated 1 year, 3 months ago by
Ernest Marcinko.
-
AuthorPosts
-
February 18, 2025 at 6:38 pm #52960
samuelepellizzari
ParticipantHi Ernest,
I was wondering if there were a way to show/hide results based on a metafield indicating the date.
More specifically, I set up my ‘events’ CPT with the ‘start-date’ metafield: this is coded in standard UNIX timestamp format. I would like to show only the results whose ‘start-date’ is greater or equal to today.
Is that possible?
Many thanks,
SamueleFebruary 19, 2025 at 11:36 am #52968Ernest Marcinko
KeymasterHi Samuele,
Yes – it is possible two ways – one is a bit of custom code snippet, or if you are not using the search filters, then that is also an option. Search filters are effective even if they are invisible.
Therefore you can create a date filter on that field like so: https://i.imgur.com/rGCSVpw.png
This will filter out results where the “start-date” is before today.February 19, 2025 at 2:27 pm #52972samuelepellizzari
ParticipantHi Ernest,
Many thanks for your reply.
Your link seems broken.
Anyway, I would rather go for the code snippet way, since I’m not using filters for the time being.
Have you got anything ready that I can tweak?
Thanks,
Samuele
February 19, 2025 at 7:34 pm #52976Ernest Marcinko
KeymasterSure Samuele! I would also prefer a custom code snippet if I were you, good choice 🙂
This is what you are looking for:
add_filter("asp_query_args", "asp_query_args_apply_date", 10, 2); function asp_query_args_apply_date($args, $search_id) { $args['post_meta_filter'][] = array( 'key' => 'start-date', 'value' => strtotime("today", time()), 'operator' => '>=', 'allow_missing' => false ); return $args; }Try adding this code via the Code Snippets plugin or to the functions.php file in your theme/child theme directory – make sure to have a full server back-up first for safety. For more details you can check the safe coding guidelines.
February 20, 2025 at 8:14 am #52990samuelepellizzari
ParticipantHi Ernest,
Many thanks indeed for sharing the snippet.
I forgot to to add a detail: the plugin is set up to search through 3 different CPTs (events, products and people, i.e. the authors of our books) and works pretty well by also grouping the results. However, with your snippet activated, I get ‘events’ results only, the ones that feature such ‘start-date’ metafield.
Shall I edit the last part as follows?
'allow_missing' => trueWould that be enough or do I need to add anything else?
Thanks again,
Samuele
February 20, 2025 at 10:19 am #52992Ernest Marcinko
KeymasterHi Samuele,
'allow_missing' => trueshould do the trick. It will allow results where the custom field does not exist and apply the filter where it does. -
AuthorPosts
- You must be logged in to reply to this topic.