2014-10-16 70 views
0

以下代碼將檢查產品ID 117是否在購物車中。如果是,那麼它會顯示額外的結賬字段。基於變量ID的Woocommerce變量結算字段

我想弄清楚如何轉換這段代碼,而不是檢查產品ID它檢查變量ID。我有兩個產品,每個都有兩個變量。我希望表單字段可見的變量ID是7509和7529.我試過了所有我能想到的內容,並且在選擇這些變量時似乎無法填充這些字段。

此代碼爲http://wordimpress.com/create-conditional-checkout-fields-woocommerce/

/** 
* Add the field to the checkout 
**/ 
add_action('woocommerce_after_order_notes', 'wordimpress_custom_checkout_field'); 

function wordimpress_custom_checkout_field($checkout) { 

//Check if Book in Cart (UPDATE WITH YOUR PRODUCT ID) 
$book_in_cart = wordimpress_is_conditional_product_in_cart(117); 

//Book is in cart so show additional fields 
if ($book_in_cart === true) { 
    echo '<div id="my_custom_checkout_field"><h3>' . __('Book Customization') . '</h3><p style="margin: 0 0 8px;">Would you like an inscription from the author in your book?</p>'; 

    woocommerce_form_field('inscription_checkbox', array(
     'type' => 'checkbox', 
     'class' => array('inscription-checkbox form-row-wide'), 
     'label' => __('Yes'), 
    ), $checkout->get_value('inscription_checkbox')); 

    woocommerce_form_field('inscription_textbox', array(
     'type' => 'text', 
     'class' => array('inscription-text form-row-wide'), 
     'label' => __('To whom should the inscription be made?'), 
    ), $checkout->get_value('inscription_textbox')); 

    echo '</div>'; 
} 

} 

/** 
* Check if Conditional Product is In cart 
* 
* @param $product_id 
* 
* @return bool 
*/ 
function wordimpress_is_conditional_product_in_cart($product_id) { 
//Check to see if user has product in cart 
global $woocommerce; 

//flag no book in cart 
$book_in_cart = false; 

foreach ($woocommerce->cart->get_cart() as $cart_item_key => $values) { 
    $_product = $values['data']; 

    if ($_product->id === $product_id) { 
     //book is in cart! 
     $book_in_cart = true; 

    } 
} 

return $book_in_cart; 

} 

發現我會很感激,可給予任何幫助。先謝謝你。

回答

1

所有需要的數據存儲在車,改變

if ($_product->id === $product_id) {

if ($_product->variation_id === $product_id) {

檢查多個variation_id的它們傳遞作爲數組,如你以下因爲它向調用函數發送1(真),所以早先嚐試不起作用。

wordimpress_is_conditional_product_in_cart(7509 || 7529) // This is incorrect, see @Howlin's answer for the correct way

+0

工作很好!哇,非常感謝你。必須將in_array添加到您的代碼中並且工作正常。謝謝阿南德! – 2014-10-17 13:39:50

3

使用in_array應該工作。

所以改變

$book_in_cart = wordimpress_is_conditional_product_in_cart(117); 

通過與產品ID的數組。

$book_in_cart = wordimpress_is_conditional_product_in_cart(array(117,113)); 

然後改變

if ($_product->id === $product_id) { 

來檢查產品ID是在數組中。

if (in_array($_product->id, $product_id)) { 

如果購物車中的產品位於數組中,則會顯示該額外字段。

+0

我想查找變量ID不是產品ID。我有兩個產品有兩個變化。我需要每個產品的第二個變量的附加字段。變量ID是7509和7529. – 2014-10-16 23:29:19

+0

謝謝你的幫助Howlin! – 2014-10-17 13:40:24