Display two post types ordered by two custom fields

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.

Leave a Comment