我在产品订单上添加了一个额外的字段,以便在订购特定产品时允许自定义注释。但是,它为每个产品添加了这个字段。我希望它仅添加特定产品类别的自定义字段。类别 ID=29。任何帮助将不胜感激。
// Display custom field on single product page
function d_extra_product_field(){
$value = isset( $_POST ['extra_product_field'] ) ? sanitize_text_field( $_POST['extra_product_field'] ) : '';
printf( '<div><label>%s</label><br><textarea name="extra_product_field" value="%s"></textarea></div>', __( 'Notes: Select colours & quantities for 12 pack only' ), esc_attr( $value ) );
}
add_action( 'woocommerce_after_add_to_cart_button', 'd_extra_product_field', 9 );
// Display custom field on single product page
function d_extra_product_field(){
$value = isset( $_POST ['extra_product_field'], $product_cat_id = 29 ) ? sanitize_text_field( $_POST['extra_product_field'] ) : '';
printf( '<div><label>%s</label><br><textarea name="extra_product_field" value="%s"></textarea></div>', __( 'Notes: Select colours & quantities for 12 pack only' ), esc_attr( $value ) );
}
add_action( 'woocommerce_after_add_to_cart_button', 'd_extra_product_field', 9 );
您可以使用 WooCommerce
WC_Product
get_category_ids()
方法,如下所示,从已定义的产品类别 ID 中定位特定产品:
add_action( 'woocommerce_after_add_to_cart_button', 'd_extra_product_field', 9 );
function d_extra_product_field() {
global $product;
if ( in_array( 29, $product->get_category_ids() ) ) {
printf( '<div><label>%s</label><br><textarea name="extra_product_field" value="%s"></textarea></div>',
__( 'Notes: Select colours & quantities for 12 pack only' ),
isset($_POST['extra_product_field']) ? sanitize_text_field( $_POST['extra_product_field'] ) : '' );
}
}
或者您可以使用WordPress
has_term()
功能如下:
add_action( 'woocommerce_after_add_to_cart_button', 'd_extra_product_field', 9 );
function d_extra_product_field() {
if ( has_term( 29, 'product_cat' ) ) {
printf( '<div><label>%s</label><br><textarea name="extra_product_field" value="%s"></textarea></div>',
__( 'Notes: Select colours & quantities for 12 pack only' ),
isset($_POST['extra_product_field']) ? sanitize_text_field( $_POST['extra_product_field'] ) : '' );
}
}
两种方法都应该有效。