So there’s two things going on here. Firstly get_the_category()
doesn’t accept a category ID as a parameter. It accepts a post ID for which to get categories from.
Judging by your code you need to use get_category()
:
$category = get_category( get_query_var('cat') );
The other problem is that you seem to be using $cat_name
without checking if you actually have a category.
For example:
$category = get_category( $nonexistant_cat_id );
if ($category) {
$cat_name = $category->slug;
}
echo $cat_name; // Will be an undefined variable;
In that example $cat_name
isn’t being set, because get_category()
didn’t return a category. So you can only use $cat_name
if get_category()
returned a category:
$category = get_the_category( $nonexistant_cat_id );
if ($category) {
$cat_name = $category->slug;
echo $cat_name; // No longer undefined variable;
}
Or in your example, just check if $cat_name
is set in the condition before using $cat_name
:
} else if (isset($cat_name) && has_category($cat_name) && is_single() &&
!is_singular('my_post_type')){
The characterisation of this being an error that “shouldn’t be necessary” to fix is incorrect. There are several problems in your code you need to address.