phpwordpresswoocommerceproductcustom-fields

Display extra product field only for specific WooCommerce product category


I have added an extra field on the product order form to allow custom notes when ordering a specific product:

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

However, it adds this field for every single product.

I would like it to add the custom field only a specific product category (Category ID 29).

Here is my code attempt:

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

But it doesn't work. How to display this extra product field only for specific WooCommerce product category?

WooCommerce extra field example


Solution

  • You can use WooCommerce WC_Product get_category_ids() method as follows, to target specific products from a defined product category 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'] ) : '' );
        }
    }
    

    Or you can use WordPress has_term() function as follows:

    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'] ) : '' );
        }
    }
    

    Both ways should work.