wordpress - 获取 Woocommerce 变体属性

标签 wordpress woocommerce hook-woocommerce

我正在尝试在自定义产品页面上获取可变产品的变体。我有两个属性,一个用于选择尺寸,另一个用于作为样本的颜色。问题是我无法显示需要显示的属性,当我使用以下代码时,它返回尺寸或颜色的文本名称,而不是尺寸或颜色样本的选择下拉列表。有什么帮助吗?!

echo implode(', ', wc_get_product_terms( $product_id, 'pa_colors' )); 

最佳答案

这是一个简短的代码来解决你的问题,我给你完整的代码,你可以只使用你需要的。

首先是检查 get_product 函数是否存在,并检查产品类型,以使用 id 创建正确的产品对象(在我的例子中 $idProduct)。

它适用于 woocommerce 3.x,我不在 woocommerce < 3.x 上测试它。

if( function_exists('get_product') ) {
        $product = get_product( $idProduct );
        if ( $product->is_type( 'variable' ) ) {

            $product = new WC_Product_Variable( $idProduct );

            $available_variations = $product->get_available_variations(); //get all child variations
            $variation_variations = $product- >get_variation_attributes(); // get all attributes by variations

            // taxonomy           => terms
            // pa_attribute-color => array('blue', 'red', green)
            // Use ex: get_taxonomy('pa_attribute-color')->labels; to get the Name and not the slug to attributes, it can be the taxonomy
            // Use ex: get_term_by('name', 'pa_attribute-color', 'pa_attribute-color); to get the Name/label 

            $result = array( $available_variations , $attributes);  // only to see the result you can use var_dump, error_log, etc.
            //...
            //... 
        }elseif ( $product->is_type( 'bundle' ) && class_exists( 'WC_Product_Bundle' ) ) {
            $product = new WC_Product_Bundle( $idProduct );
        }else{
            $product = new WC_Product( $idProduct );
        }
    }

您也尝试使用:

$product->get_attribute( $key );
wc_attribute_label($key);

其中 $key 可以是 pa_colorpa_size

希望对你有帮助。

关于wordpress - 获取 Woocommerce 变体属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45715344/

相关文章:

wordpress - 与父级一起显示 WooCommerce 产品子类别

php - Wordpress 电子商务插件将总订单成本限制在 999,999,999

php - 从可变产品的 WooCommerce 变体中获取权重值

php - 如何获取 Woocommerce 产品库图片 URL?

php - woocommerce_thankyou Hook 函数的 fatal error 问题

javascript - 如何检测点击的元素是否不是 jQuery 元素的子元素?

php - 如何在 WordPress 中左连接 wp_terms、wp_term_relationships、wp_term_taxonomy 和 wp_termmeta 表?

php - 在 WooCommerce 中为自定义字段使用 wc_get_orders() orderby 参数

php - 如果在 WooCommerce 中自动添加包装,则在选择产品重量时不计算最终成本

php - 除 WooCommerce 中的特定产品外,最低购物车金额