Search code examples
phpwordpresscategories

how can i use "+" and "," for category_name in WP_Query?


i want my category_name to be like => "music" and "new" or "music" and "old" , to show the posts width the category ( "music" and "new" ) or ( "music" and "old" ).

i've try the code below but didn't work :

$song = array(
   "category_name" => "music+new,old",
);
$recent = new WP_Query( $song );

Solution

  • You want 2 different queries in one - combination. But category_name parameter can't understand this. For such non-simple combinations you can use taxonomy queries.

    $args = array(
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => array( 'music' ),
        ),
        array(
            'taxonomy' => 'category',
            'field'    => 'slug',
            'terms'    => array( 'new','old' ),
        ), 
    ),
    );
    $query = new WP_Query( $args );
    

    For more example you can check taxonomy code examples in official documentation.