WooCommerce apply custom text only for specific products by ID [duplicate]

Update (It seems that you are using a version of WooCommerce before version 3)

For product categories you can use has_term() Wordpress conditional function with the corresponding 'product_cat' custom taxonomy used by WooCommerce, just in your first hooked function, where you will define the allowed product category (or product categories) this way:

function kia_custom_option(){
    global $product;

    // HERE set your allowed product categories (can be IDs, slugs or names)
    $product_categories = array( 't-shirts', 'socks' );

    // Added WooCommerce retro compatibility
    $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

    if( has_term( $product_categories, 'product_cat', $product_id ) ){

        $value = isset( $_POST['_custom_option'] ) ? sanitize_text_field( $_POST['_custom_option'] ) : '';
        printf( '<label>%s</label><input name="_custom_option" value="%s" />', __( 'Custom Text: ', 'kia-plugin-textdomain' ), esc_attr( $value ) );
    }
}
add_action( 'woocommerce_before_add_to_cart_button', 'kia_custom_option', 9 );

Code goes in function.php file of your active child theme (or active theme).

Tested and works (for all WC versions since 2.4). No need of anything else.


For defined product Ids the code will be:

function kia_custom_option(){
    global $product;

    // HERE set your allowed product IDs in the array
    $product_ids = array( 680, 687 );

    // Added WooCommerce retro compatibility
    $product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;

    if( in_array( $product_id, $product_ids ) ){

        $value = isset( $_POST['_custom_option'] ) ? sanitize_text_field( $_POST['_custom_option'] ) : '';
        printf( '<label>%s</label><input name="_custom_option" value="%s" />', __( 'Custom Text: ', 'kia-plugin-textdomain' ), esc_attr( $value ) );
    }
}
add_action( 'woocommerce_before_add_to_cart_button', 'kia_custom_option', 9 );

Code goes in function.php file of your active child theme (or active theme).

Tested and works (for all WC versions since 2.4).