如果产品类别等于x,则在WooCommerce结账时创建一个自定义字段



因此,只要购物车中有特定类别的产品,我就希望在WooCommerce页面的结账页面上创建/显示几个自定义字段。这些字段的值只对我以后在后端的订单中访问是必要的,不需要添加到给客户的订单电子邮件确认中。

有指针吗?如果有帮助的话,我会在我的网站上使用ACF。

提前感谢!

您需要执行以下操作:

  1. 检测购物车中的现有产品是否在您的类别中
  2. 如果符合您的条件,请在签出时添加字段
  3. 验证并保存数据
  4. 在后端显示它

文档中已经对此进行了概述,您可能需要阅读:https://woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/#adding-a定制专用场

以下是一个示例功能,用于检测购物车是否包含定义类别中的特定产品

// functions.php
function cat_in_cart( $cat_slug ) {
$cat_in_cart = false;
$cart = WC()->cart->get_cart();
if ( !$cart ) {
return $cat_in_cart;
}
foreach( $cart as $cart_item_key => $cart_item ) {
if ( has_term( $cat_slug, 'product_cat', $cart_item['product_id'] )) {
$cat_in_cart = true;
break;
}
}
return $cat_in_cart;
}

在结账时添加字段(链接到文档(:

// functions.php
/**
* Add the field to the checkout
*/
add_action( 'woocommerce_after_order_notes', 'my_custom_checkout_field' );
function my_custom_checkout_field( $checkout ) {
if ( cat_in_cart( 'your_category_slug' ) ) {
echo '<div id="my_custom_checkout_field"><h2>' . __('My Field') . '</h2>';
woocommerce_form_field( 'my_field_name', array(
'type'          => 'text',
'class'         => array('my-field-class form-row-wide'),
'label'         => __('Fill in this field'),
'placeholder'   => __('Enter something'),
), $checkout->get_value( 'my_field_name' ));
echo '</div>';
}
}

之后,在结账时保存字段:

add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['my_field_name'] )
wc_add_notice( __( 'Please enter something into this new shiny field.' ), 'error' );
}
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['my_field_name'] ) ) {
update_post_meta( $order_id, 'My Field', sanitize_text_field( $_POST['my_field_name'] ) );
}
}

最后,在仪表板上显示:

/**
* Display field value on the order edit page
*/
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta($order){
echo '<p><strong>'.__('My Field').':</strong> ' . get_post_meta( $order->id, 'My Field', true ) . '</p>';
}