0

I have two custom post types, created by two third party plugins, that I want to display by the main query in a common ordered list. They must be ordered by two distinct custom fields, but with the same info - the event start day, that are stored in the same format "Y-m-d". Bellow is my code, but it doesn't work how is expected - first are displayed event type posts, but in an aleatory unordered way, then facebook_events type posts, ordered how is expected. How can I solve this?

function add_custom_post_type_to_query( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'post', 'facebook_events', 'event' ) );
        $query->set( 'meta_query', array(
            'relation' => 'OR',
            array(
                array(
                    'key' => 'event_start_date', //this is from facebook_events post type
                    'value' => date_i18n("Y-m-d"),
                    'compare' => '>=',
                    'type' => 'DATE',
                )
            ),
            array(
                'key' => '_event_start_date', //this is from event post type
                'value' => date_i18n("Y-m-d"),
                'compare' => '>=',
                'type' => 'DATE',
            )
        ) );
        $query->set( 'orderby', 'meta_value' );
        $query->set( 'order', 'ASC' );
    }
}
add_action( 'pre_get_posts', 'add_custom_post_type_to_query' );

UPDATE

I had an enlightening! I found where my code was wrong, see my answer.

1 Answer 1

0

My old code was wrong, this is a good one, as I think:

function add_custom_post_type_to_query( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'post', 'facebook_events', 'event' ) );
        $query->set( 'meta_query', array(
            'relation' => 'OR',
            array(
                'key' => 'event_start_date', //this is from facebook_events post type
                'value' => date_i18n("Y-m-d"),
                'compare' => '>=',
                'type' => 'DATE',
            ),
            array(
                'key' => '_event_start_date', //this is from event post type
                'value' => date_i18n("Y-m-d"),
                'compare' => '>=',
                'type' => 'DATE',
            )
        ) );
        $query->set( 'orderby', 'meta_value' );
        $query->set( 'order', 'ASC' );
    }
}
add_action( 'pre_get_posts', 'add_custom_post_type_to_query' );

UPDATE

Here you will find a better solution, as it uses for ordering timestamps, that includes not only the date, but also the time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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