admin管理员组文章数量:1323348
I need to get the category id of the current post outside the loop. First I get the category based on the post id:
global $wp_query;
$postcat = get_the_category( $wp_query->post->ID );
Now how to get the category id? I tried: $cat_id = $postcat->term_id;
but it's not working.
I need to get the category id of the current post outside the loop. First I get the category based on the post id:
global $wp_query;
$postcat = get_the_category( $wp_query->post->ID );
Now how to get the category id? I tried: $cat_id = $postcat->term_id;
but it's not working.
5 Answers
Reset to default -1function catName($cat_id) {
$cat_id = (int) $cat_id;
$category = &get_category($cat_id);
return $category->name;
}
function catLink($cat_id) {
$category = get_the_category();
$category_link = get_category_link($cat_id);
echo $category_link;
}
function catCustom() {
$cats = get_the_category($post->ID);
$parent = get_category($cats[1]->category_parent);
if (is_wp_error($parent)){
$cat = get_category($cats[0]);
}
else{
$cat = $parent;
}
echo '<a href="'.get_category_link($cat).'">'.$cat->name.'</a>';
}
USE <a href="<?php catLink(1); ?>"> <?php catName(1); ?>
When you use get_the_category()
function to get category's data, it return the array of object so you have to access category id by passing array key, like this $postcat[0]->term_id
global $post;
$postcat = get_the_category( $post->ID );
// try print_r($postcat) ;
if ( ! empty( $postcat ) ) {
echo esc_html( $postcat[0]->name );
}
Hope this help!
Old post I know, but wp_get_post_categories
is likely what you want.
$cats = wp_get_post_categories( get_the_ID(), array( 'fields' => 'ids' ) );
This will return an array of category IDs like so
array (size=3)
0 => int 13
1 => int 15
2 => int 120
So if you just want one category ID, you can get that from the first key in the array of category IDs.
$category_id = $cats[0];
An improvement to Govind Kumar answer, as the asker askes about category ID, not the category name. The property name of the object for category ID is "cat_ID".
// get cat ID for general view
$postcat = get_the_category( $query->post->ID );
if ( ! empty( $postcat ) ) {
echo $postcat[0]->cat_ID;
}
global $post; $postcat = get_the_category( $post->ID ); if ( ! empty( $postcat ) ) { foreach ($postcat as $nameCategory) { echo $nameCategory->name .' '; } }?>
本文标签: categoriesHow to get category id of current post
版权声明:本文标题:categories - How to get category id of current post? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742128907a2422068.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论