【问题标题】:Woocommerce Product category id from product id来自产品 ID 的 Woocommerce 产品类别 ID
【发布时间】:2016-03-20 09:37:23
【问题描述】:

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

请帮忙:-|

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

【问题讨论】:

  • 您要为该类别设置折扣的“手动更改价格”是什么意思?

标签: woocommerce categories product


【解决方案1】:

这是一个从产品 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;
}

【讨论】:

  • @GilJosef 如果答案帮助您尝试接受它并放弃投票..干杯
【解决方案2】:

一般来说:

/**
 * 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' );

【讨论】:

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