2017-10-06 182 views
1

我在我的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

回答

1

這是一個代碼示例,您可能需要定製一點點。這段代碼:

  • 顯示臨時定製(用於測試目的),有喜歡的自定義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