在WooCommerce变量产品单页中获取所选的产品变体ID

mar*_*n87 2 php wordpress jquery variations woocommerce

对于我的Woocommerce变量产品,我在单个产品页面上实现了自定义大小的选择器,并在表格中具有以下尺寸:

在此输入图像描述

这些变化只是:30B 30C 30D而不是被分成:30B C D

我想弄清楚的是:如何抓住每个产品变化的运输类?

我在购物车页面上有类似的内容,但我不知道变体ID是什么或如何从单个产品页面获取它:

$product_id = ( 0 != $cart_item['variation_id'] ) ? $cart_item['variation_id'] : $cart_item['product_id'];
// need the variation id for the above to be able to do the rest:

$product_shipping_classes = get_the_terms( $product_id, 'product_shipping_class' );
$product_shipping_class_name = ( $product_shipping_classes && ! is_wp_error( $product_shipping_classes ) ) ? current( $product_shipping_classes )->name : '';
Run Code Online (Sandbox Code Playgroud)

我知道如果有变体ID,该怎么做.我只是无法弄清楚如何得到它以便做其余的事情.我需要得到的唯一东西是产品ID和变体的slug(这个页面上还有一个颜色属性).

但是我已经为产品提供了一个默认的变体(所以variation_id设置了隐藏).

也许需要首先获取所选颜色的ID然后获取其他颜色的变化ID?

Loi*_*tec 6

在可变产品的WooCommerce产品单页中,您无法在PHP中获得所选的产品变体,因为它是一个实时事件(客户端,而不是服务器端).

这样做的方法是使用JavaScript/jQuery来获取它.由于您没有为此单一产品页面提供有关您的可变产品的任何相关代码,因此我无法为您提供完全符合您需求的实际工作代码.

在变量产品的单个产品页面上获取所选变体ID (在此示例中,我在添加到购物车按钮下方动态显示所选变体ID):

add_action( 'woocommerce_single_product_summary', 'single_product_variable_customization', 3, 0 );
function single_product_variable_customization() {
    global $product;

    // Only for variable products on single product pages
    if ( $product->is_type('variable') && is_product() ) {

    ##  ==>  ==>  Here goes your php code (if needed)  ==>  ==>  ##

    // Passing a variable to javascript
    $string1 = "The selected Variation ID is: ";
    $string2 = "No Variation ID is selected ";
    ?>
    <script>
    jQuery(document).ready(function($) {

        // Initializing
        var myText1 = '<?php echo $string1; ?>', myText2 = '<?php echo $string2; ?>';

        // Get and display the default variation ID after add-to-cart button (initialization)
        if( '' != $('input.variation_id').val() )
            $('div.woocommerce-variation-add-to-cart').after('<div class="selected-variation-id">'+myText1+$('input.variation_id').val()+'</div>');
        else
            $('div.woocommerce-variation-add-to-cart').after('<div class="selected-variation-id">'+myText2+'</div>'); // No ID selected

        console.log($('input.variation_id').val()); // Output in the browser console


        // Get and display the chosen variation ID after add-to-cart button
        $('select').blur( function(){
            if( '' != $('input.variation_id').val() )
                $('div.selected-variation-id').html(myText1+$('input.variation_id').val());
            else
                $('div.selected-variation-id').html(myText2); // No ID selected

            console.log($('input.variation_id').val()); // Output in the browser console
        });
    });
    </script>
    <?php
    }
}
Run Code Online (Sandbox Code Playgroud)

代码放在活动子主题(或主题)的function.php文件中,或者放在任何插件文件中.

此代码在WooCommerce 3+下进行测试并且有效.

因此,在此基础上,您可以根据自己的要求制作自己的功能(因为您不再提供必要的详细信息或代码).

一些相关的答案示例用法(使用jQuery和Woocommerce单个产品页面):