WooCommerce get category slug - Undefined property notice with a function

我只是一个虾纸丫 提交于 2020-08-19 12:58:07

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/38550471/woocommerce-get-category-slug-undefined-property-notice-with-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!