skip to Main Content

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 class="woo_variable_custom_message">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 class="woo_variable_custom_message">Hello</div>';
}

`

2

Answers


  1. Chosen as BEST ANSWER

    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 class="woo_variable_custom_message">Hello</div>';
            }
        } 
    

  2. 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 class="woo_variable_custom_message">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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search