1

I have the following arguments for a WP_Query:

$args = array(
    'post_type' => array( 'cpt-1', 'cpt-2' ),
    'post_status' => 'publish',
    'posts_per_page' => 9,
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'key-1',
            'compare' => 'NOT EXISTS'
        ),
        array(
            'key' => 'key-1',
            'value' => 1,
            'compare' => '!='
        )
    ),
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'ctax-1',
            'field' => 'slug',
            'terms' => 'term-1',
            'operator' => 'NOT IN'
        ),
        array(
            'taxonomy' => 'ctax-2',
            'field' => 'slug',
            'terms' => 'term-2',
            'operator' => 'NOT IN'
        )
    ),
);

Now I would like to add to the loop the custom post type cpt-3 but only if its posts has the custom field value of the custom meta key-2 set to 1.

Is it possible?

  • Don't you want to modify the query instead? – cybmeta Feb 21 '18 at 10:08
0

If the key-2 is uniquely assigned to cpt-3 post type, then you can add another meta query argument to your query arguments:

array(
    'key'     => 'key-2',
    'value'   => 1,
    'compare' => '='
)

If not, you can run another query, and then merge them as follows:

$final_query = array_merge( (array) $query_1, (array) $query_2 );

But, you should use get_posts() instead of WP_Query() since you can't merge objects with methods. The get_posts() returns an array of posts which can be merged.

However you should notice, meta queries are expensive and will slow down your website ( probably ).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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