在 WooCommerce 结账时为特定产品类别制作订单备注

Make order notes required for specific product categories in WooCommerce checkout

我需要做订单备注,只需要某些产品类别(例如,如果有人购买“卡片”,他们必须填写消息)。

我发现这个片段需要做订单备注,我只需要将它设置为与特定产品相关联。

// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );

// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
     $fields['order']['order_comments']['required'] = true;
     return $fields;
}

以下将使特定产品类别所需的结帐订单备注字段:

// Conditional function that check for specific product(s) category(ies)
function is_product_category_terms_in_cart( $categories ) {
    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
            return true;
        }
    }
    return false;
}

// Make order notes required field conditionally
add_filter( 'woocommerce_checkout_fields' , 'make_order_notes_required_field' );
function make_order_notes_required_field( $fields ) {
    // Set in the array your targeted product category term(s)
    $categories = array("cards");

    if ( is_product_category_terms_in_cart( $categories ) ) {
        $fields['order']['order_comments']['required'] = true;
    }
    return $fields;
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。