Home > Software engineering >  Warning: Undefined property: WP_Error::$category_count
Warning: Undefined property: WP_Error::$category_count

Time:12-05

Am trying to build a web and am encountering this error

Warning: Undefined property: WP_Error::$category_count in category.php on line 64

$category = get_category($tag);
$count = $category->category_count;
$catName = get_cat_name( $tag );
function classiera_Cat_Ads_Count(){     
        $cat_id = get_queried_object_id();
        $cat_parent_ID = isset( $cat_id->category_parent ) ? $cat_id->category_parent : '';
        if ($cat_parent_ID == 0) {
            $tag = $cat_id;
        }else{
            $tag = $cat_parent_ID;
        }
        $q = new WP_Query( array(
            'nopaging' => true,
            'tax_query' => array(
                array(
                    'taxonomy' => 'category',
                    'field' => 'id',
                    'terms' => $tag,
                    'include_children' => true,
                ),
            ),
            'fields' => 'ids',
        ) );
    $count = $q->post_count;
    return $count; 
}

Searched the web but without any luck. Any help will be much appreciated.

CodePudding user response:

It looks like the code is trying to access a property called category_count on an object of type WP_Error, but that property does not exist on that object.

The get_category() function is used to retrieve a category object for a given category ID. If the category does not exist, this function will return a WP_Error object instead of a category object.

To fix this error, you can add a check to make sure that the $category variable is not an instance of WP_Error before trying to access the category_count property:

$category = get_category($tag);
if ( !is_wp_error( $category ) ) {
    $count = $category->category_count;
    $catName = get_cat_name( $tag );
} else {
    // Handle the error
}

This will prevent the error from occurring and allow your code to continue executing. You may want to add some additional error handling to deal with the situation where the get_category() function returns an error.

Hope that helps!

  • Related