get_the_category()
should either be used within a (post) loop or with a $post_id
parameter. In your code $cat_now
is probably at the moment an empty array, so there’s nothing at the 0 position.
Also, get_the_category()
returns an array of WP_Term
objects, which don’t have a property called , which have category_parent
, but just parent
.parent
property that you should use.
If you want to list child categories for a certain category in category.php
, then the following code should work.
/**
* For category.php
*/
$current_category = get_queried_object(); // should be WP_Term object in this context
$category_list="";
// $current_category->parent is 0 (i.e. empty), if top level category
if ( ! empty( $current_category->parent ) ) {
$category_list = wp_list_categories(array(
'child_of' => $current_category->parent,
));
// var_dump($category_list);
}
And just for fun, example for getting children of the first category of a post.
/**
* Used e.g. in single.php
* get_the_id() is not required, if get_the_category() is used in the Loop
*/
$current_categories = get_the_category( get_the_id() ); // Array of WP_Term objects, one for each category assigned to the post.
$category_list="";
if ( ! empty( $current_categories[0]->parent ) && $current_categories[0]->parent ) {
$category_list = wp_list_categories(array(
'child_of' => $current_categories[0]->parent,
));
// var_dump($category_list);
}