Home > Enterprise >  How to target a certain product in woocomerce if it is a Variation
How to target a certain product in woocomerce if it is a Variation

Time:11-08

I'm trying to figure out how to target a specific variable product in woocommerce to show this message underneath the "Add to cart" button. The current code is showing for all variable product type.

`

add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message' , 10, 0 );
function custom_product_message() {
    global $product;

    if( ! $product->is_type( 'variable' )) return; // Only for variable products

    echo '<div >Hello</div>';
}

`

This is the snippet I am working on.`

add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message' , 10, 0 );
function custom_product_message() {
    global $product;

    if( ! $product->is_type( 'variable' )) return; // Only for variable products

    echo '<div >Hello</div>';
}

`

CodePudding user response:

Found out this can target Variable or simple product type using this way.

add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message', 20 );
     
    function custom_product_message() {
    if ( is_single( '8941' )) {
        echo '<div >Hello</div>';
        }
    } 

CodePudding user response:

Global and dynamic solution is create a custom field in product and you can custom text field.

You can create custom field by custom code or you can use ACF plugin to create custom field in the product.

Custom code to create custom field: https://www.cloudways.com/blog/add-custom-product-fields-woocommerce/

ACF plugin: https://wordpress.org/plugins/advanced-custom-fields/

Then using below action hook you can make the process dynamic from admin itself using one time code.

add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message', 20 );
     
    function custom_product_message() {
    global $product;

    $getcustomText = get_post_meta(post_id, 'meta_key', true);
    if ( !empty ($getcustomText)) {
        echo '<div >Hello</div>';
        }
    }

Quick Note: I know process is little big, but it will never give you trouble some or make again and again coding to add variable product id or other parameter in the theme functions file

Thanks

  • Related