构建一个函数来获取WooCommerce中产品ID的产品类别ID

时间:2016-09-02 12:07:21

标签: php wordpress woocommerce categories product

我想在WooCommerce中获取产品的产品类别ID。我正在使用 WP All import-export插件,我可以编写自定义函数。在具有产品ID或名称的自定义功能中,我想查询 category id

在主题的functions.php文件中,我可以添加如下所示的函数,并从产品ID中获取类别ID:

function my_get_category_id_from_product_id($product_id) {

    // do something to find the category to which my product belongs to and return it.

    return $category_id;
}

我怎样才能做到这一点?

由于

1 个答案:

答案 0 :(得分:3)

WooCommerce中的产品并不总是只有一个类别。您还可以为产品ID设置多个类别。这是一个函数,它将返回字符串中给定产品ID的类别ID,但如果此给定产品ID的多个类别,它将返回此产品的所有类别ID的昏迷单独字符串。

以下是代码:

function get_my_prod_cat_ids($prod_id) {

    $terms = get_the_terms( $prod_id, 'product_cat' );
    if($terms) {
        foreach ($terms as $key => $term) {
            $cats_ids_array[$key] = $term->term_id;

            //To get only the first category (uncomment below)
            //break;
        }
        // to get an array replace below by: $output = $cats_ids_array;
        $output = implode( ",", $cats_ids_array ); 
        echo $output;
    }
}

此代码经过测试并正常运行。

当然,此代码会出现在您的活动子主题(或主题)或任何插件文件的function.php文件中。

相关问题