php 从帖子 ID 中获取类别名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17303840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get Category name from Post ID
提问by user1937021
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!
谢谢!
回答by M Khalid Junaid
here you go get_the_category( $post->ID );
will return the array of categories of that post you need to loop through the array
在这里,您get_the_category( $post->ID );
将返回该帖子的类别数组,您需要遍历该数组
$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}
回答by kaimagpie
echo '<p>'. get_the_category( $id )[0]->name .'</p>';
is what you maybe looking for.
是您可能正在寻找的。
回答by Kortschot
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);
?>
回答by Nuker
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;
}
回答by swapnesh
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);
回答by Heniek
<?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="" />';
}
}
?>