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.
function 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="https://wordpress.stackexchange.com/questions/247859/<?php catLink(1); ?>"> <?php catName(1); ?>