I was trying to fix some warnings and I noticed that I get constantly
PHP Notice: Undefined variable:
If I use :
$categories = get_the_category(get_query_var('cat'));
$cat_name = $categories[0]->slug;
or/with
$categories = get_category(get_query_var('cat'));
$category_id = $categories->term_id;
$category_slug = $categories->slug;
$title_page = $categories->name;
I use it in loops or conditionals
like:
$args1 = array(
'no_found_rows' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'category__in' => array($category_id),
'posts_per_page' => 2,
'ignore_sticky_posts' => true,
'post_type' => 'any'
);
or/and
} else if (has_category($cat_name) && is_single() &&
!is_singular('my_post_type')){
I always will get with Debug Mode True, that kind of Warning
So I started to work around it to get some kind of solution, and I noticed that I really didn't understand quite well the difference between get_the_category();
and get_category();
Then I tried :
$cat0 = get_category( get_query_var('cat'));
if(isset($cat0)) {
$cat1 = get_category(get_query_var('cat'));
$category_id = $cat1->term_id;
$category_slug = $cat1->slug;
$title_page = $cat1->name;
}
or/and
$cat4 = get_the_category(get_query_var('cat'));
if(!isset($cat4)){
$categories = get_the_category(get_query_var('cat'));
$cat_name = $categories[0]->slug;
}
if(isset($cat4) && is_single()){
$categories = get_the_category(get_query_var('cat'));
$cat_name = $categories[0]->slug;
}
but of course if get_category
or get_the_category
in ==
NULL
I will get again PHP Notice: Undefined variable: cat_name
What am I missing?