问题描述
我只需要对某些产品类别(例如,如果某人购买“卡片”,他们必须填写一条消息)就需要订购记录。
我已经找到了此片段来制作需要的订单注释,我只需要将其设置为与某个产品相关联即可。
// 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文件中。经过测试,可以正常工作。