I use this function to convert the woocommerce category id into a category slug
function woocommerceCategorySlug($id){
$term = get_term( $id, \'product_c
The get_term() function could return a WP_Error object if the term wasn't found, which is exactly the problem reported by the error you cited.
While the answer submitted by @LoicTheAztec works, the most direct approach might be to bake in some defensive programming. Here are a couple of ways:
function woocommerceCategorySlug( $id )
{
$term = get_term( $id, 'product_cat' );
if( is_wp_error( $term ) || !is_object( $term ) || !property_exists( $term, 'slug' ) )
return null;
return $term->slug;
}
Now, if get_term()
returns a WP_Error
object, or not an object at all, or the expected object doesn't have a 'slug' property, then return null. Otherwise, return the slug.
Alternatively, you could have the get_term()
function return the result as an associative array and simplify the checks a bit:
function woocommerceCategorySlug( $id )
{
$term = get_term( $id, 'product_cat', ARRAY_A );
return isset( $term['slug'] ) ? $term['slug'] : null;
}
In this version, isset()
serves a dual purpose: to see if the slug exists in the expected array, or fail silently if $term
isn't an array in the first place.