获取 WooCommerce 变量产品属性选择值

Get WooCommerce Variable Product attribute selected value

我在我的 woocommerce 单品页面中添加了两个属性,"Metal" 和 "Ring Size"。它们 "variations" 是我产品页面上的下拉选项。

我希望能够点击我的按钮,我能够抓取选定的值并将其放到我的 URL 参数。

我解决了所有问题,直到抓取的值不正确。

到目前为止我已经试过了,但它只是给我一个可能的属性列表 values/selections 而不是单个选定值..

$metal = $product->get_attribute( 'Metal' );

http://example.com/?metal=18K%20White%20Gold%20|%2018K%20Yellow%20Gold%20|%20Rose%20Gold%20|%20Platinum

我只想要我在下拉菜单中选择的内容,如下所示:

http://example.com/?metal=Platinum

这是一个代码示例,您可能需要对其进行一些自定义。此代码将:

  • 显示带有自定义 href 值的临时自定义按钮(用于测试目的),例如:
    home-url/?metal=home-url 是您的网站 url)
  • 从您的 "metal" 属性中获取选定的值并将其附加到按钮 URL。

代码如下:

add_filter( 'woocommerce_single_variation', 'get_variation_selectected_value', 25 );
function get_variation_selectected_value() {
    global $product;

    // Display button (Just for testing purpose) 
    // You can remove or comment the line of code below …
    // But you need to set your url like: http://example.com/?metal=
    echo '<br /><a href="'.home_url("/?metal=").'" class="book-now button">'. __('Make an Appointment Now') .'</a>';

    // The script
    ?>
    <script>
    jQuery(document).ready(function($) {
        // Get the default value
        var selectedValue = $('select#metal option:checked').val(),
            hrefAttribute = $('a.book-now').attr("href");
            $('a.book-now').attr("href", hrefAttribute+selectedValue);

        // Display on browser console (for test)
        console.log($('a.book-now').attr("href"));

        // Get the live selected value
        $('select#metal').blur( function(){
            selectedValue = $('select#metal option:checked').val();
            hrefAttribute = $('a.book-now').attr("href");
            $('a.book-now').attr("href", hrefAttribute+selectedValue);

            // Display on browser console (for test)
            console.log($('a.book-now').attr("href"));
        });
    });
    </script>
    <?php
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

代码已经过测试(使用另一个属性)并且可以正常工作。