Patrick Moore
Patrick Moore

Reputation: 13354

WordPress WP_Query: Display custom post type based on custom meta value, and also order on another custom meta value

I am using the WordPress plug-ins Advanced Custom Fields, and Custom Post Type UI.

I have built a WP_Query to display a particular post type, filtered by a particular custom field value.

$loop = new WP_Query( array( 
    'post_type' => 'news', 
    'meta_key' => 'news_story_type', 
    'meta_value' => 'release', 
    'posts_per_page' => 3 
) );

I now want to sort the resulting posts by another custom field, date_of_publication rather than use WordPress's menu_order or date. The ACF documentation says to specify orderby and meta_key in the query args.

$args = array(

'post_type' => 'event',

'posts_per_page' => -1,

'meta_key' => 'start_date',

'orderby' => 'meta_value_num',

'order' => 'DESC' );

But alas, doing so conflicts with the meta_key I've already supplied to filter.

Has anyone encountered this before and found a solution?

Upvotes: 1

Views: 3472

Answers (1)

Steve
Steve

Reputation: 20469

Try using meta_query

$loop = new WP_Query( array( 
    'post_type' => 'news', 
    'meta_key' => 'start_date',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'posts_per_page' => 3,
    'meta_query' => array(
        array('key' => 'news_story_type', 'value' => 'release')
     )
) );

Upvotes: 3

Related Questions