【问题标题】:Building a function to get the product category ID of a product ID in WooCommerce构建一个函数来获取 WooCommerce 中产品 ID 的产品类别 ID
【发布时间】:2017-01-10 13:11:03
【问题描述】:

我正在尝试在 WooCommerce 中获取产品的产品类别 ID。我正在使用 WP All 导入导出插件,我可以在其中编写自定义函数。在具有产品 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;
}

我怎样才能做到这一点?

谢谢

【问题讨论】:

  • 你的问题不清楚。您可以发布您尝试实现此目的的代码吗?
  • 在主题的 functions.php 文件中,我可以添加如下所示的函数并从产品 ID 中获取类别 ID: function my_get_category_id_from_product_id($product_id) { // 做一些事情来找到我的类别产品属于并退回。返回 $category_id; }

标签: php wordpress woocommerce categories product


【解决方案1】:

WooCommerce 中的产品并不总是只有一个类别。一个产品 ID 还可以有多个类别。这是一个函数,它将在 string 中返回给定产品 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 文件中或任何插件文件中。

【讨论】:

    猜你喜欢
    • 2016-03-20
    • 1970-01-01
    • 2016-01-09
    • 2015-05-27
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    相关资源
    最近更新 更多