首页 > 解决方案 > Wordpress 将 woocommerce 类别作为数组获取

问题描述

我需要将所有类别放在一个数组中以自动将产品添加到类别中,但我失败了:/我有这个代码:

function getCats($catlist, $name) {

        $regex = '('.implode('|', $catlist).')';
        $success = preg_match_all($regex, $name, $matches);
        return $success ? $matches[0] : [];   

}

在其他功能中:

        $catlist = get_terms( array(
        'taxonomy' => 'product_cat',
        'hide_empty' => false,
        ) );            


        $firstCat = getCats($catlist, $name)[0];

但如果我运行代码,我会收到以下消息:

WP_Term无法将类的对象转换为字符串

有谁知道我如何处理它以将所有类别保存在一个字符串中?

标签: wordpress

解决方案


我检查过get_terms()函数返回错误:

WP_Error 对象([错误] => 数组([invalid_taxonomy] => 数组([0] => 无效分类。))[error_data] => 数组())

$catlist = get_terms( array(
        'taxonomy' => 'product_cat',
        'hide_empty' => false,
        ) );  

这就是它给出错误的原因:

WP_Term 类的对象无法转换为字符串

注意:请先Invalid taxonomy使用https://wordpress.stackexchange.com/questions/13480/get-terms-return-errors解决错误,然后它会自动解决。


推荐阅读