1

I have a custom post type which I can set a start and end date in the metadata.

I use the function below to filter the search results and only show results from the post type visitor:

function SearchFilter($query) {
        if ($query->is_search) {
            $query->set('post_type', 'visitor');
        }
        return $query;
    }
add_filter('pre_get_posts', 'SearchFilter');

I have two metadata fields that contains a start date and an end date:

get_post_meta( get_the_ID(), 'visitor-start-date', true ); // Start date
get_post_meta( get_the_ID(), 'visitor-date', true ); // End date

I want to filter the search results to only show results if the current date (today) is between these two dates. The dates are in epoch/unix and looks like this: 1539129600 1546214400

How do I include this in my filter I created above to only show results where todays date is between the start and end date?

1

You can use meta queries to filter posts according to your needs.

Here is a sample code:

function SearchFilter( $query ) {
    if ( !is_admin() && $query->is_search ) {
        $query->set( 'post_type', 'visitor' );

        $query->set( 'meta_query', array(
            'relation' => 'AND',
            array(
                'key' => 'visitor-start-date',
                'value' => time(),
                'compare' => '<='
            ),
            array(
                'key' => 'visitor-date',
                'value' => time(),
                'compare' => '>='
            ),
        ) );
    }
}
add_action( 'pre_get_posts', 'SearchFilter' ); // pre_get_posts is an action, not a filter, so you don't have to return anything in it

If you want the server time, then use time function as in code above.

On the other hand, if you need to use WP time in comparisons, then use current_time function:

current_time( 'timestamp' );
7
  • Sadly I couldn't make it work? Could it be because it is a custom post type metadata (the visitor-start-date and visitor-date)? I get no search results at all now. And I have checked that I have posts which match the criteria. For example one post with start and end date 1539129600 1546214400 which is 2018-10-10 to 2018-12-31. – joq3 Nov 1 '18 at 13:28
  • Hmm... It should work. Try to replace compare methods. – Krzysiek Dróżdż Nov 1 '18 at 13:30
  • Yes, that was it, switched them around! Thank you so much! – joq3 Nov 1 '18 at 13:34
  • By the way is time() using the server time or will it compare to the timezone you have selected in Wordpress? – joq3 Nov 1 '18 at 13:35
  • OK, I've updated the code in my answer, so compare params are set correctly. I've also addressed your timezone question. (If the answer is correct, then remember to mark it as solution, so site stays tidy). – Krzysiek Dróżdż Nov 1 '18 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.