0

So I am trying to WP_Query all post type of "triextras"

There are 2 types of "triextras" categorised by taxonomy: news (id:22) and events (id:21)

Events has custom field event_date.

When I query Triextras Events I should use:

$args = array(
    'post_type' => 'triextras',
    'posts_per_page' => get_field('limit'),
    'tax_query' => array(
        array(
            'taxonomy' => 'triextras-category',
            'field' => 'term_id',
            'terms' => '22',
        )
    ),
    'meta_key'          => 'event_date',
    'orderby'           => 'meta_value',
    'order'             => 'DESC'
);
$posts_wp = new WP_Query($args);

That works fine.

For news, the sorting will be based on the post_date DESC which i think is the default sorting of Wordpress, so the args will become:

$args = array(

    'post_type' => 'triextras',
    'posts_per_page' => get_field('limit'),

    'tax_query' => array(
        array(
            'taxonomy' => 'triextras-category',
            'field' => 'term_id',
            'terms' => '21',
        ),
    ),

);
$posts_wp = new WP_Query($args);

Which works great too.

Now, the thing is, I want to merge the listing, showing both events and news, and sort them either by event_date (if it exist) if not sort by post_date

Based on the solution on this question, I can have the result by using:

$args = array(
    'post_type' => 'triextras',
    'orderby' => 'meta_key',
    'order' => 'ASC',
    'meta_query' => array(
        'relation' => 'OR',
        array( 
            'key'=>'event_date',
            'compare' => 'EXISTS'           
        ),
        array( 
            'key'=>'post_date',
            'compare' => 'NOT EXISTS'           
        )
    ),
    'post_per_page'=>-1
);

But I am not getting any result. I'd been working with this for hours and I cannot seem to get the actual solution.

Hope somebody can help.

Regards,

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.