0

I have a custom taxonomy how-to-guide-type and I have some terms setup in this taxonomy.

I want to display ONLY the posts assigned to each taxonomy term.

I have the following but I can only seem to display posts for the first taxonomy term not for each different one:

        $returnable = [];
        $custom_terms = get_terms('how-to-guide-type');


        $query = new WP_Query([
            'post_type' => 'cpt_how_to_guides',
            'orderby' => 'date',
            'order' => 'ASC',
            'tax_query' => [
                [
                    'taxonomy' => 'how-to-guide-type',
                    'field' => 'slug',
                    'terms' => $custom_terms[0]->slug,
                ],
            ],
        ]);


        if ($query->have_posts()) {
            $counter = 1;
            while ($query->have_posts()) {
                $query->the_post();

                $returnable[] = [
                    'date' => get_the_date('d M Y'),
                    'title' => get_the_title(),
                    'link' => get_the_permalink(),
                    'content' => get_post_content(),
                    'count' => $counter
                ];
                $counter++;
            }
        }


        wp_reset_query();

        return $returnable;

I have tried to for each through the terms too but this displays all posts irrespective of which term they are assigned to. I want the query to be able to dynamically figure this out without having to add the slugs for the terms in the terms => parameter.

1
  • How is your question different from just getting all the posts of a given taxonomy?
    – klewis
    Commented Feb 1, 2019 at 16:22

1 Answer 1

0

If you only need to display posts assigned to a taxonomy (just a list of posts from each term in your taxonomy without displaying term information)

Get only terms IDs:

$custom_terms = get_terms( array(
    'taxonomy' => 'how-to-guide-type', //your taxonomy
    'hide_empty' => true, //ignore terms without posts
    'fields' => 'ids' //return only terms ids
));

Now $custom_terms is an array of terms ids. Modify your tax_query like this:

$query = new WP_Query([
    'post_type' => 'cpt_how_to_guides',
    'orderby' => 'date',
    'order' => 'ASC',
    'tax_query' => [
        [
            'taxonomy' => 'how-to-guide-type',
            'terms' => $custom_terms, //array with terms ids of your taxonomy
            'operator' => 'AND' //display posts from all of these terms
        ],
    ],
]);

Also, you don't need to create a custom variable for a counter, your $query has a property for this purpose. Use $query->current_post instead of a $counter variable. It starts from zero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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