Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce get category slug - Undefined property notice with a function

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?

like image 327
sonia maklouf Avatar asked Dec 24 '22 03:12

sonia maklouf


1 Answers

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:

  • Code Reference > Function get_term_by()
  • Can't get category object in some templates of WooCommerce
like image 64
LoicTheAztec Avatar answered Dec 26 '22 17:12

LoicTheAztec