WordPress – SQL request with WP_Query, use OR between post_type and taxonomy

My issue is pretty simple, I’m trying to get both portfolio posts (from a plugin) and articles that have the “portfolio” category (made myself).

$args = array(
    'post_type' => 'portfolio',
    'tax_query' => array(
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => 'portfolio',
        )
    )
);

$query = new WP_Query($args);

It looks like the relationship between post_type and tax_query is an AND, I’d need an OR, how can I do that?

Read More

I tried following the official documentation but I’m stuck. (https://codex.wordpress.org/Class_Reference/WP_Query)
Thanks for the help.

Related posts

2 comments

  1. Here is an example with a relation ‘OR’:

    $args = array(
        'post_type' => 'portfolio',
        'meta_query' => array(
            'relation' => 'OR', /* <-- here */
            array(
                'key' => 'color',
                'value' => 'blue',
                'compare' => 'NOT LIKE'
            ),
            array(
                'key' => 'price',
                'value' => array( 20, 100 ),
                'type' => 'numeric',
                'compare' => 'BETWEEN'
            )
        )
    );
    $query = new WP_Query( $args );
    
  2. I haven’t found any solution using only one query. (couldn’t change the AND to OR).

    So I’ve made two queries instead:

    $query1 = new WP_Query(array('post_type' => 'portfolio'));
    $query2 = new WP_Query(array(
        'tax_query' => array(
            array(
                'taxonomy' => 'category',
                'field'    => 'slug',
                'terms'    => 'portfolio',
            )
        )));
    
    $query = merge_WP_queries($query1, $query2);
    
    function merge_WP_queries(WP_Query $query1, WP_Query $query2){
        $wp_query_returned = new WP_Query();
        $wp_query_returned->posts = array_merge( $query1->posts, $query2->posts );
    
        //populate post_count count for the loop to work correctly
        $wp_query_returned->post_count = $query1->post_count + $query2->post_count;
    
        return $wp_query_returned;
    }
    

    It works correctly, even though it’s not what I’d like to use.

Comments are closed.