pre_get_posts meta compare not working in admin list tables
-
Hi, I hate it when I can’t figure out the code, but I can’t get this to work.
On my events custom post type admin list table, I added a filter with restrict_manage_posts to allow a user to select beginning and ending dates for the events.
I’m trying to do a meta query, but despite the selections it returns all posts.
function filterquery( $admin_query ){ global $pagenow; if ( is_admin() && $admin_query->is_main_query() && in_array( $pagenow, array( 'edit.php' ) ) && ( ! empty( $_GET['DateFrom'] ) || ! empty( $_GET['DateTo'] ) ) ) { $start = sanitize_text_field( $_GET['DateFrom'] ); $end = sanitize_text_field( $_GET['DateTo'] ); $custom_meta = array( 'meta_key' => 'start_date', 'meta_value' => array( $start, $end ), // format: '20200701', '20201231' 'meta_compare' => 'BETWEEN', 'type' => 'DATE', ); $admin_query->set( 'meta_query', $custom_meta ); } return $admin_query; }
Ive verified that the query vars are properly set:
[query] => Array ( [s] => [paged] => 1 [order] => asc [orderby] => menu_order title [post_type] => events [posts_per_page] => -1 . . . (edited for brevity) [meta_query] => Array ( [meta_key] => start_date [meta_value] => Array ( [0] => 20200701 [1] => 20201231 ) [meta_compare] => BETWEEN [type] => DATE )
I would really appreciate some help. Thanks.
-
You’re using old style query vars within the newer “meta_query”, hence the query vars are not correctly set, they merely reflect your flawed expectations. For example, “meta_key” should just be “key”. Review the docs on using the correct key names for “meta_query”.
https://developer.wordpress.org/reference/classes/wp_query/
Find the custom fields section link in the contents. (direct links from here don’t work right due to hidden content on the docs page)@bcworkz Good catch, thanks, but still not working. Query vars now show:
[meta_query] => Array ( [key] => start_date [value] => Array ( [0] => 20201101 [1] => 20210531 ) [compare] => BETWEEN [type] => DATE )
but I’m still getting all records found.
Problem solved: meta_query is an array of arrays
$custom_meta = array( array( 'key' => 'start_date', 'value' => array( $start, $end ), // change to how "event date" is stored 'compare' => 'BETWEEN', 'type' => 'DATE', ) );
- The topic ‘pre_get_posts meta compare not working in admin list tables’ is closed to new replies.