从帖子ID获取类别名称

问题描述 投票:0回答:8

是否可以根据给定的帖子 ID 获取类别的类别名称,以下代码可以获取类别 Id,但是如何获取名称?

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

谢谢!

php wordpress categories
8个回答
56
投票

在这里

get_the_category( $post->ID );
将返回您需要循环遍历该数组的帖子的类别数组

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

获取类别


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

可能是您正在寻找的。


5
投票

没有

<?php get_the_category( $id ) ?>

在循环内就这样做吗?

对于室外:

global $post;
$categories = get_the_category($post->ID);
var_dump($categories);

3
投票
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;
}

这是函数的第二个参数

wp_get_post_categories()
您可以传递接收数据的属性。

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

1
投票

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

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

0
投票

使用

get_the_category()
功能。

$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories);

0
投票
     <?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="" />';
            }       
}
?>

-1
投票

第一个类别名称(按帖子 ID)

$first_category = wp_get_post_terms( get_the_ID(), 'category' )[0]->name;
© www.soinside.com 2019 - 2024. All rights reserved.