WooCommerce get category slug - Undefined property notice with a function

前端 未结 2 1224
北恋
北恋 2021-01-19 11:29

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

function woocommerceCategorySlug($id){
    $term = get_term( $id, \'product_c         


        
2条回答
  •  -上瘾入骨i
    2021-01-19 12:08

    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.

提交回复
热议问题