Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php WooCommerce get category slug-带有函数的未定义属性通知_Php_Wordpress_Woocommerce_Categories_Product - Fatal编程技术网

Php WooCommerce get category slug-带有函数的未定义属性通知

Php WooCommerce get category slug-带有函数的未定义属性通知,php,wordpress,woocommerce,categories,product,Php,Wordpress,Woocommerce,Categories,Product,我使用此函数将woocommerce类别id转换为类别slug function woocommerceCategorySlug($id){ $term = get_term( $id, 'product_cat' ); return $term->slug; } 这是可行的,但问题是我收到了通知 有没有办法避免这种情况?解决这个问题的有效方法是使用WordPress本机函数get\u term\u by(),并以这种方式在代码中转置它: function

我使用此函数将woocommerce类别id转换为类别slug

function woocommerceCategorySlug($id){
    $term = get_term( $id, 'product_cat' );
    return $term->slug;       
}
这是可行的,但问题是我收到了通知


有没有办法避免这种情况?

解决这个问题的有效方法是使用WordPress本机函数
get\u term\u by()
,并以这种方式在代码中转置它:

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

如果找不到术语,函数可能会返回一个对象,这正是您引用的错误报告的问题

尽管@LoicTheAztec提交的答案是可行的,但最直接的方法可能是加入一些烤肉。以下是几种方法:

选择1 现在,如果
get\u term()
返回
WP\u错误
对象,或者根本不是对象,或者预期对象没有“slug”属性,则返回null。否则,返回slug

选择2 或者,您可以让
get_term()
函数以关联数组的形式返回结果,并稍微简化检查:

function woocommerceCategorySlug( $id )
{
    $term = get_term( $id, 'product_cat', ARRAY_A );

    return isset( $term['slug'] ) ? $term['slug'] : null;
}
在这个版本中,
isset()
有两个用途:查看slug是否存在于预期的数组中,或者如果
$term
最初不是数组,则以静默方式失败

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;
}
function woocommerceCategorySlug( $id )
{
    $term = get_term( $id, 'product_cat', ARRAY_A );

    return isset( $term['slug'] ) ? $term['slug'] : null;
}