WP_Query search by meta_key and category_name

Tags: ,



I see how to do multiple meta_keys or multiple category_names, but how do I combine them?

    $args = array(
        'post_type' => 'quotes',
        'meta_key'   => 'newsletter',
        'meta_value' => '1',
        'category_name' => 'dogs',
    );
    $query1 = new WP_Query( $args );

Answer

You can use tax_query and meta_query.

$args = array(
    'post_type' => 'quotes',
    'meta_key'   => 'newsletter',
    'meta_value' => '1',
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field'    => 'name',
            'terms'    => 'bob',
        )
    ),
    'meta_query' => array(
        array(
            'key'     => 'newsletter',
            'value'   => 1,
            'compare' => 'LIKE'
        )
    ),
);
$query1 = new WP_Query( $args );


Source: stackoverflow