5

I use this function to convert the woocommerce category id into a category slug

function woocommerceCategorySlug($id){
    $term = get_term( $id, 'product_cat' );
    return $term->slug;       
}

This is working, but the problem is that i'm getting a notice

Notice: Undefined property: WP_Error::$slug 

Is there a way to avoid this notice?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
sonia maklouf
  • 2,713
  • 4
  • 18
  • 28

2 Answers2

11

The working solution for this is to use WordPress native function get_term_by() and to transpose it in your code this way:

function woocommerceCategorySlug( $id ){
    $term = get_term_by('id', $id, 'product_cat', 'ARRAY_A');
    return $term['slug'];       
}

Reference:

Community
  • 1
  • 1
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
1

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:

Option 1

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.

Option 2

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.

Matthew Clark
  • 1,885
  • 21
  • 32