仅显示特定 WooCommerce 产品类别的额外产品字段

问题描述 投票:0回答:1

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

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

但这不起作用。如何仅针对特定的 WooCommerce 产品类别显示此额外的产品字段?

WooCommerce extra field example

php woocommerce custom-fields
1个回答
0
投票

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

两种方法都应该有效。

© www.soinside.com 2019 - 2024. All rights reserved.