Is it possible to get the category name of a category given the Post ID, the following code works to get the Category Id, but how can I get the name?
<?php $post_categories = wp_get_post_categories( 4 ); echo $post_categories[0]?>Thank!
8 Answers
here you go get_the_category( $post->ID ); will return the array of categories of that post you need to loop through the array
$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
} 2 echo '<p>'. get_the_category( $id )[0]->name .'</p>';is what you maybe looking for.
4doesn't
<?php get_the_category( $id ) ?>do just that, inside the loop?
For outside:
<?php
global $post;
$categories = get_the_category($post->ID);
var_dump($categories);
?> 2 function wp_get_post_categories( $post_id = 0, $args = array() )
{ $post_id = (int) $post_id; $defaults = array('fields' => 'ids'); $args = wp_parse_args( $args, $defaults ); $cats = wp_get_object_terms($post_id, 'category', $args); return $cats;
}Here is the second argument of function wp_get_post_categories()
which you can pass the attributes of receiving data.
$category_detail = get_the_category( '4',array( 'fields' => 'names' ) ); //$post->ID
foreach( $category_detail as $cd )
{ echo $cd->name;
} 1 You can a single line to echo out the category name by passing the post ID simply by using this:
echo wp_get_post_terms(get_the_ID(), 'category')[0]->name;
Use get_the_category() function.
$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories); 4 <?php // in woocommerce.php $cat = get_queried_object(); $cat->term_id; $cat->name; ?> <?php // get product cat image if ( is_product_category() ){ $cat = get_queried_object(); $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true ); $image = wp_get_attachment_url( $thumbnail_id ); if ( $image ) { echo '<img src="' . $image . '" alt="" />'; }
}
?> First Category name by post id
$first_category = wp_get_post_terms( get_the_ID(), 'category' )[0]->name; 6