Last active
November 22, 2023 09:45
-
-
Save markhowellsmead/2bb4abdc8b718ee3e20c7cc4cf58be6b to your computer and use it in GitHub Desktop.
Complex WordPress meta query by start and end date (custom meta fields)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Complex WordPress meta query by start and end date (custom meta fields) | |
* Intended for use on the `pre_get_posts` hook. | |
* Caution; this makes the query very slow - several seconds - so should be | |
* implemented with some form of caching. | |
* | |
* mark@sayhello.ch 22.10.2019, based on code from 201 onwards | |
*/ | |
add_action('pre_get_posts', [$this, 'onlyFutureEntries']); | |
… | |
public function onlyFutureEntries($query) | |
{ | |
if (!is_admin() && isset($query->query['post_type']) && $query->query['post_type'] === 'sht_event') { | |
$query->set('orderby', 'meta_value'); | |
$query->set('order', 'ASC'); | |
$query->set('meta_key', 'start_date'); | |
$meta_query = (array) $query->get('meta_query'); | |
$meta_query[] = [ | |
'relation' => 'OR', | |
[ | |
// Start date and end date are empty | |
'relation' => 'AND', | |
[ | |
'relation' => 'OR', | |
[ | |
'key' => 'start_date', | |
'value' => '', | |
'compare' => '=' | |
], | |
[ | |
'key' => 'start_date', | |
'compare' => 'NOT EXISTS' | |
] | |
], | |
[ | |
'relation' => 'OR', | |
[ | |
'key' => 'end_date', | |
'value' => '', | |
'compare' => '=' | |
], | |
[ | |
'key' => 'end_date', | |
'compare' => 'NOT EXISTS', | |
] | |
] | |
], | |
[ | |
// Start date >= today and end date empty | |
'relation' => 'AND', | |
[ | |
'key' => 'start_date', | |
'value' => date('Y-m-d'), | |
'compare' => '>=', | |
'type' => 'DATE' | |
], | |
[ | |
'key' => 'end_date', | |
'value' => '', | |
'compare' => '=' | |
] | |
], | |
[ | |
// Start date <= today and end date >= today | |
'relation' => 'AND', | |
[ | |
'key' => 'start_date', | |
'value' => date('Y-m-d'), | |
'compare' => '<=', | |
'type' => 'DATE' | |
], | |
[ | |
'key' => 'end_date', | |
'value' => date('Y-m-d'), | |
'compare' => '>=', | |
'type' => 'DATE' | |
] | |
] | |
]; | |
$query->set('meta_query', $meta_query); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello Mark, would you have a minute to spare to help me with implementing your snippet to my case, I got myself in a real struggle. Thanks.