You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅为特定WooCommerce产品类别显示额外产品字段

实现WooCommerce特定产品类别显示自定义字段

我在产品订单表单中添加了一个额外字段,用于订购特定产品时填写自定义备注,初始代码如下(该字段会显示在所有产品页面):

// 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 );

我希望仅为ID为29的特定产品类别显示该自定义字段,尝试了以下代码但无法正常工作:

// 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 );

正确实现方式

要仅在指定产品类别(ID=29)的页面显示自定义字段,需要在函数中添加类别判断逻辑,利用WooCommerce的has_term()函数检查当前产品是否属于目标类别:

// Display custom field only for specific product category
function d_extra_product_field(){
    // 获取当前产品ID
    $product_id = get_the_ID();
    
    // 检查当前产品是否属于ID为29的产品类别
    if ( has_term( 29, 'product_cat', $product_id ) ) {
        $value = isset( $_POST['extra_product_field'] ) ? sanitize_text_field( $_POST['extra_product_field'] ) : '';
        printf( '<div><label>%s</label><br><textarea name="extra_product_field">%s</textarea></div>', __( 'Notes: Select colours & quantities for 12 pack only' ), esc_textarea( $value ) );
    }
}
add_action( 'woocommerce_after_add_to_cart_button', 'd_extra_product_field', 9 );

关键说明

  • has_term( 29, 'product_cat', $product_id ):该函数用于验证当前产品是否属于指定的产品类别(参数分别为类别ID、分类法名称、产品ID)。
  • 修正了textarea的写法:textarea的内容应放在标签内部而非value属性中,同时使用esc_textarea()来安全转义用户输入内容。
  • 只有当产品属于目标类别时,才会输出自定义字段,其他产品页面不会显示。

内容的提问来源于stack exchange,提问作者Steve Roberts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 03:12:16