Php 构建函数以获取WooCommerce中产品ID的产品类别ID
我正在尝试获取WooCommerce中产品的产品类别id。我使用的是WP-All-import-export插件,在那里我可以编写自定义函数。在具有产品id或名称的自定义函数中,我要查询它的Php 构建函数以获取WooCommerce中产品ID的产品类别ID,php,wordpress,woocommerce,categories,product,Php,Wordpress,Woocommerce,Categories,Product,我正在尝试获取WooCommerce中产品的产品类别id。我使用的是WP-All-import-export插件,在那里我可以编写自定义函数。在具有产品id或名称的自定义函数中,我要查询它的类别id 在theme的functions.php文件中,我可以添加如下函数,并从产品id获取类别id: function my_get_category_id_from_product_id($product_id) { // do something to find the category t
类别id
在theme的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;
}
我怎样才能做到这一点
感谢在商业中,一种产品并不总是只有一个类别。对于一个产品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文件或任何插件文件中。您的问题并不清楚。您可以发布您试图实现这一点的代码吗?在theme的functions.php文件中,我可以添加如下函数并从产品id获取类别id:function my_get_category_id_from_product_id($product_id){//做些什么来查找我的产品所属的类别并返回它。return$category_id;}