I have an "activity" custom post type, that has start and end dates introduced via custom fields. I want to add a meta_query argument through pre_get_posts, to get "activity" posts between two dates.

The problem, is that the end date custom field ("act__date_end_day") is not always declared, sometimes (90%) is left blank so its value doesn't exists in the DB, and I cannot check for the existence of it, since we are on pre_get_posts...

How can I write it, to get the correct posts when "act__date_end_day" doesn't exists?

add_action( 'pre_get_posts', 'wpse_modify_query_args' );
function wpse_modify_query_args( $query ) {

    if ( $query->is_main_query() && !is_admin() ) {

        if ( $query->is_post_type_archive('activity') ) {
            $query->set('orderby', 'meta_value_num');  
            $query->set('meta_key', 'act__date_start_day');  
            $query->set('order', 'ASC');
            $query->set('posts_per_page', 12);

            $metaquery = array(
                'relation' => 'AND',
                    'key'       => 'act__date_start_day',
                    'compare'   => '>=',
                    'value'     => date("Ymd"),
                    'type'      => 'DATE'
                    'key'       => 'act__date_end_day',
                    'compare'   => '<=',
                    'value'     => date("Ymd"),
                    'type'      => 'DATE'
            $query->set( 'meta_query', $metaquery );



  • Between what dates you want to get activity posts? – anton Feb 6 at 18:00

Your Answer

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

Browse other questions tagged or ask your own question.