简体   繁体   English

从帖子 ID 中获取类别名称

[英]Get Category name from Post ID

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?是否可以根据帖子 ID 获取类别的类别名称,以下代码可用于获取类别 ID,但如何获取名称?

<?php $post_categories = wp_get_post_categories( 4 ); echo $post_categories[0]?>

Thank!谢谢!

here you go get_the_category( $post->ID );给你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;
}

get_the_category get_the_category

echo '<p>'. get_the_category( $id )[0]->name .'</p>';

是您可能正在寻找的。

doesn'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);
?>
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.这是函数wp_get_post_categories()的第二个参数,您可以传递接收数据的属性。

$category_detail = get_the_category( '4',array( 'fields' => 'names' ) ); //$post->ID
foreach( $category_detail as $cd )
{
   echo $cd->name;
}

Use get_the_category() function.使用get_the_category()函数。

$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories);
     <?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="" />';
            }       
}
?>

您可以通过简单地使用以下命令传递帖子 ID 来在一行中回显类别名称:

echo wp_get_post_terms(get_the_ID(), 'category')[0]->name;

按帖子 id 列出的第一个类别名称

$first_category = wp_get_post_terms( get_the_ID(), 'category' )[0]->name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM