来自产品ID的Woocommerce产品类别ID

时间:2015-12-14 19:20:58

标签: woocommerce categories product

我正在尝试使用产品ID获取产品页面中的主要类别ID但没有成功。

请帮忙: - |

我必须知道产品是否属于X类并手动更改价格

2 个答案:

答案 0 :(得分:0)

以下是从产品ID

获取woo-commerce类别ID的示例

获取产品页面的类别

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
    $product_cat_id = $term->term_id;
    break;
}

答案 1 :(得分:0)

一般来说:

/**
 * Get products categories given a product ID.
 *
 * @author Nabil Kadimi
 * @link   https://stackoverflow.com/a/46714456/358906
 *
 * @param  Integer $product_id The product ID.
 * @param  String  $fields     Which fields to retrieve all, ids, names,
 *                             count, id=>parent, id=>slug or id=>name.
 *                             See WP_Term_Query constructor for more info.
 * @return Array               The categories.
 */
function so34274948_wc_get_categories_by_product_id( $product_id, $fields ) {
    return wp_get_post_terms( $product_id, 'product_cat', [ 'fields' => $fields ] );
}

示例:

$categories = so34274948_wc_get_categories_by_product_id( 123, 'ids' );