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?

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

1 Answer 1

1

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 and acknowledge that you have read and understand our privacy policy and code of conduct.

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