Filtering admin entries for custom post type

I have a post type events, which has column event_date on admin edit page. Event date is a meta data saved by a custom field in the format “2016-12-31”. I have made a select box with filters for month / year of my events, just like the default WordPress filter for posts based on their creation dates. My question is: how can I make them work? What filters should I use? I though like intercept que query and configure the meta query just I would do in a “raw” WP_Query, but I don’t know how.

1 Answer
1

You can use the pre_get_posts hook – the following code assumes your input name is event_date, and the values are in the format YYYY-MM.

It runs a few checks (is the input non-empty, are we in the admin, is this the main query, and is this for events?) before generating a meta query, which is an SQL IN for all the possible dates within the specified month:

add_action( 'pre_get_posts', function ( $wp_query ) {
    if (
        ! empty( $_REQUEST['event_date'] ) &&
        is_admin() &&
        $wp_query->is_main_query() &&
        $wp_query->get( 'post_type' ) === 'events'
    ) {
        // Assuming $_REQUEST['event_date'] is in the format YYYY-MM
        $year_month = $_REQUEST['event_date'];
        $dates      = [];

        for ( $day = 1; $day <= 32; $day++ ) {
            $dates[] = "$year_month-$day";
        }

        $wp_query->set( 'meta_query', [[
            'key'     => 'event_date',
            'compare' => 'IN',
            'value'   => $dates,
        ]]);
    }   
});

Leave a Comment