我在产品订单表上添加了一个额外的字段,以便在订购特定产品时允许自定义注释:

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

然而,它 for each 产品添加了该字段.

我希望它仅添加特定产品类别(类别ID 29)的自定义字段.

这是我的代码try :

// 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产品类别显示此额外产品字段?

WooCommerce extra field example

推荐答案

您可以使用以下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'] ) : '' );
    }
}

这两种方式都应该有效.

Php相关问答推荐

Laravel变形 map 不适用于扩展模型

为WooCommerce中的特定用户角色指定促销价格

输入手写CSV时在PHP中进行日期判断

使用WooCommerce本机产品短码时不考虑价格筛选(_SHORT CODE)

PHP中的圆生成器在国际日期变更线上失败

在WooCommerce中设置带有国家/地区和年份前缀的顺序序号

如何实现对数据库表中多列的唯一约束?

Apache只允许index.php-不从根目录工作

如何在Livewire 3 Form类中做依赖注入?

使用ESI的Symfony Sulu清漆

如何配置我的.env文件以在laravel的一个项目中连接两个不同的数据库?

Mockery在模拟Redis连接时抛出错误:Mockery\Exception\BadMethodCallException

除WooCommerce中的特定国家/地区外,有条件地要求填写邮政编码 checkout 字段

扩展 WooCommerce 类触发未捕获错误:未找到WC_Coupon类

execute_query 和prepare+execute 有什么区别?

Woocommerce 临时购物车税未根据第一个请求正确计算

WooCommerce 回购自定义插件:如何更新用户钱包?

使用 Eloquent 更新现有的外键值

无法在 Laravel 10 中安装 jenssegers/mongodb

PHP Loop 在迭代中使用修改后的数据