Reputation: 1054
I have a loop for a custom post type an all is working well, except I cannot return the actual category name that the post has assigned to it.
I have the following code:
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'portfolio',
'orderby' => 'menu_order',
'order' => 'ASC'
));
if($posts) {
foreach($posts as $post) {
setup_postdata( $post );
?>
<div>
<div class="mix <?php get_cat_name( ); ?>" ><img src="<?php the_field('portfolio_image'); ?>" alt=""></div> <!-- ACF -->
</div>
<?php
}
}
wp_reset_postdata();
?>
This is just one of the WP Codex functions I have tried including tring all with echo. I imagine my problem is something else? Many thanks in Advance.
Upvotes: 0
Views: 1336
Reputation: 3614
Replace your code
from
get_cat_name( );
to
$categories = get_the_terms($post->ID,'custom-texonomy-name');
$cat = key($categories);
echo $categories[$cat]->name;
Upvotes: 0
Reputation: 3362
According to the codex an id is required for this method (https://codex.wordpress.org/Function_Reference/get_cat_name). Leaving out the id will not work.
One solution would be to use get_the_category($postId)
to retrieve the category for your post (https://codex.wordpress.org/Function_Reference/get_the_category). You can leave out the postId here
post_id (integer) (optional) The post id. Default: $post->ID (The current post ID)
Note that the method returns an object - not the category name. You can try the following code to see if it's working:
<?php
$category = get_the_category();
echo $category[0]->cat_name;
?>
Upvotes: 3
Reputation: 325
try this code
<?php $terms = get_the_terms($post->ID, 'TAXONOMY' );
if ($terms && ! is_wp_error($terms)) :
$term_slugs_arr = array();
foreach ($terms as $term) {
$term_slugs_arr[] = $term->name;
}
$terms_slug_str = join( " ", $term_slugs_arr);
endif;
echo $terms_slug_str;?>
Upvotes: 0