是否可以根据给定的帖子 ID 获取类别的类别名称,以下代码可以获取类别 Id,但是如何获取名称?
<?php $post_categories = wp_get_post_categories( 4 ); echo $post_categories[0]?>
谢谢!
在这里
get_the_category( $post->ID );
将返回您需要循环遍历该数组的帖子的类别数组
$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}
echo '<p>'. get_the_category( $id )[0]->name .'</p>';
可能是您正在寻找的。
没有
<?php get_the_category( $id ) ?>
在循环内就这样做吗?
对于室外:
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;
}
这是函数的第二个参数
wp_get_post_categories()
您可以传递接收数据的属性。
$category_detail = get_the_category( '4',array( 'fields' => 'names' ) ); //$post->ID
foreach( $category_detail as $cd )
{
echo $cd->name;
}
您可以使用以下命令通过传递帖子 ID 来单行回显类别名称:
echo wp_get_post_terms(get_the_ID(), 'category')[0]->name;
使用
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)
$first_category = wp_get_post_terms( get_the_ID(), 'category' )[0]->name;