以下代码检查产品ID 117是否在购物车中。如果是,则显示其他结帐字段。
我正在试图弄清楚如何转换此代码,而不是检查产品ID,它检查变量ID。我有两个产品,每个产品有2个变量。我希望表单字段可见的变量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;
}
我很感激可以给予任何帮助。提前谢谢。
答案 0 :(得分: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) ) {
如果购物车中的产品在数组中,则会显示这些更改,然后会显示该额外字段。
答案 1 :(得分:1)
所有必需的数据都存储在购物车中,更改
if ( $_product->id === $product_id ) {
到
if ( $_product->variation_id === $product_id ) {
要检查多个variation_id将它们作为数组传递,您之前尝试过的以下内容将无效,因为它向调用函数发送1(true)。
wordimpress_is_conditional_product_in_cart(7509 || 7529) // This is incorrect, see @Howlin's answer for the correct way