MelbDev
MelbDev

Reputation: 375

how to get categories of posts within Custom Post Type

I have Custom Post Type called "football_teams" which has 20 posts.

// WP_Query arguments
$args = array(
    'post_type'              =>  'football_teams',
    'posts_per_page'         =>  '-1'
);

// The Query
$query = new WP_Query( $args );

how do I get categories of all those posts within the CPT.

I've tried $cats = get_categories(); but it shows all the categories of all posts.

I've also tried $cats = get_categories($args); but didnt work.

Any help would be appreciated, I'm new to web-development.

Upvotes: 0

Views: 7786

Answers (1)

Paul Janubas
Paul Janubas

Reputation: 136

You can simply use the get_the_terms() function to get the term(category) name. You can use the code below. Note: the $taxonomy is your custom taxonomy. If you are not using custom taxonomy then it would be category.

<?php

$post_type = 'your post type';
$taxonomy = 'your taxonomy';

$args = [
    'post_type' => $post_type,
    'posts_per_page' => -1
];

$query = new WP_Query($args);

if( $query->have_posts() ) {

    while( $query->have_posts() ) {
        $query->the_post();

        $terms = get_the_terms($post->ID, $taxonomy);
        $categories = [];

        if( $terms ) {          
            foreach ($terms as $category) {
                $categories[] = $category->name;
            }       
        }

        $categories = implode(', ', $categories);

        echo get_the_title() .'| '. $categories .' <br>';
    }
}


Sample output:
my post 1 | category1, category2, category3
my post 2 | category2, category4, category5

Upvotes: 7

Related Questions