php - 结帐时的 WooCommerce 自定义字段

标签 php wordpress woocommerce checkout

我想在 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>';

}

最佳答案

感谢 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;

}

关于php - 结帐时的 WooCommerce 自定义字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34557439/

相关文章:

php - GET 和 POST 在同一个页面上?

php - 将多个 PHP 变量放入 Javascript 数组中

php - Woocommerce 可变产品下拉列表

php - 在自定义插件错误问题中扩展 WC_Product 类(找不到 WC_Product 类)

php - 使用 php 验证多个 mysql 行之间的 true

php - 我将如何在 PHP 中缓存分页内容

php - MySQL:查询中的条件语句

php - 在 WooCommerce 中将爱尔兰的邮政编码结帐字段设置为必填字段

mysql - 尝试在 ubuntu 上设置 wordpress 并想在 mysql 中授予权限

php - 使 Woocommerce 自定义结帐字段不可编辑