获取WooCommerce变量产品属性选定的值

问题描述:

我在我的woocommerce单品页面中添加了“Metal”和“Ring Size”两个属性。它们是“变体”,因此它们可以在我的产品页面上下拉选择。获取WooCommerce变量产品属性选定的值

我希望能够在我的点击按钮,我可以能够抢选定值,并把它放到我的URL参数。

我解决了一切,直到抓取的值不正确。

到目前为止我试过,但它仅仅是给我的这个属性可能值/选择,而不是单一的选择值列表..

$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 
+0

使用你以前的代码,我只是想通过PHP,因为它所有在一起......我不知道该怎么做,因为我认为在下拉列表中选择的值将被保存或进入“服务器”一次你点击“预约按钮”。有没有办法“回声”下拉按钮?所以我可以在PHP中工作?但我想它很难,因为选择需要改变图像和价格... – pkmangg

这是一个代码示例,您可能需要定制一点点。这段代码:

  • 显示临时定制(用于测试目的),有喜欢的自定义href的值按钮:
    home-url/?metal= ... home-url是你的网站URL)
  • 从你的“金属”获得选择的值属性并将其附加到按钮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文件或也以任何插件文件。

该代码已经过测试(与另​​一个属性),只是工程。

+0

谢谢,完美的作品!如果我要将“戒指大小”下拉列表添加到网址,它会是什么?我试图改变这一点,它不起作用。是否因为“Ring Size”输入错误(空格)?$('select#ring_size')。blur(function(){0}选择值= $('select#ring_size选项:checked').val(); hrefAttribute = $('a.book-now')。attr(“href”); $('a.book-now')。attr(“href”,hrefAttribute +'&ring ='+ selectedValue); }); – pkmangg

+0

@pkmangg您已删除实时链接...所以我不知道 – LoicTheAztec

+0

我发现它,它的“戒指尺寸”。所以现在我尝试自己做 - 因为我想要http://example.com/?metal=platinum&ringsize=3。这是我做的,但它给了我怪异的URL,当我选择这两个选项“http://example.com/?metal=Platinum&ringsize=&metal=Platinum&ringsize=13” – pkmangg