Reputation: 375
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
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