结账中的 WooCommerce 自定义字段

5

我希望在WooCommerce结账页面上添加自定义字段,但仅适用于特定产品。

例如,如果客户购物车中仅有产品A,则此自定义字段应仅出现在WooCommerce结账页面中。

我正在使用以下代码在functions.php中添加自定义字段:

add_action('woocommerce_before_order_notes', 'my_delivery_checkout_field');

function my_delivery_checkout_field( $checkout ) {

echo '<div id="my_local_club"><h3>'.__('Delivery Options').'</h3>';

woocommerce_form_field( 'delivery_options', array(
'type' => 'select',
'class' => array('my-club-class form-row-wide'),
'label' => _('<br><br>Please select your options', 'woocommerce'),
'required' => true,
'placeholder' => _x('Please Select An Option...', 'placeholder','woocommerce'),
'options' => array(
'option1' => 'Option 1',
'option_2' =>'Option 2',
 'option_3' =>'Option 3'
)
), $checkout->get_value( 'delivery_options' ));

echo '</div>';

}

交付选项可能最好通过(非常强大的)配送系统来处理。 - random_user_name
嗨,cale_b,实际上这不是关于交付选项的问题,客户想在结账页面添加额外的用户输入字段,只是为了得到通知。 - Bilal Naseer
1个回答

2
所以以下代码解决了我的问题,感谢StackOverFlow.com。
/**
* Add the field to the checkout
**/
add_action('woocommerce_before_order_notes', 'my_delivery_checkout_field');

function my_delivery_checkout_field( $checkout ) {

    //Check if gift card is in cart
    $book_in_cart = conditional_product_in_cart( 7267 );

if ( $book_in_cart === true ) {
echo '<div id="my_local_club"><h3>'.__('Delivery Options').'</h3>';

woocommerce_form_field( 'delivery_options', array(
'type' => 'select',
'class' => array('my-club-class form-row-wide'),
'label' => _('<br><br>Please select your options', 'woocommerce'),
'required' => true,
'placeholder' => _x('Please Select An Option...', 'placeholder','woocommerce'),
'options' => array(
'option1' => 'Option 1',
'option_2' =>'Option 2',
 'option_3' =>'Option 3'
)
), $checkout->get_value( 'delivery_options' ));

echo '</div>';
}
}




// Check if Gift card is in the cart

function 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;

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接