Search code examples
arrayswordpressloopstaxonomycustom-taxonomy

Wordpress Loop Tax Query with multiple terms


I have a taxonomy called "fachbereiche". First I load the taxonomies of the current page:

<?php $term_list = wp_get_post_terms($post->ID, 'fachbereiche', array("fields" => "all", 'parent' => '0'));

    foreach($term_list as $thisslug)
    {
        $output =  $thisslug->slug;
        echo $output;

?>

The current page has the taxonomy slugs: "bauelemente" and "baumarkt". The echo $output returns bauelementebaumarkt.

Now I want to find all posts of a custom post type "marken" with the same taxonomies as we got above ("bauelemente" and "baumarkt"), so I load the following query:

<?php
        $loop = new WP_Query(
        array(
            'post_type' => 'marken',
            'post_status'=>'publish',
            'posts_per_page'=>-1,
            'orderby'=> 'title',
            'order'=>'ASC',
            'tax_query' => array(
                array(
                    'taxonomy' => 'fachbereiche',
                    'field' => 'slug',
                    'terms' => array($output)
                ),
            ),
        )
        );

    }
?>

The query returns only the posts with the taxonomy for "baumarkt". I think because the variable $output returns bauelementebaumarkt. I think that you have to seperate "bauelemente" and "baumarkt". Please have in mind that there can be more than 2 terms or just 1.


Solution

  • Your $output should be an array instead of string, so add this before foreach:

    $output = array();
    

    Then inside foreach you should do this:

    $output[] =  $thisslug->slug;
    

    And finally in tax_query it should be like this:

    'terms' => $output,