4

In WooCommerce, I am trying to add an extra add to cart button below product summary. I successfully added an extra button following this code which works for single products:

add_action( 'woocommerce_single_product_summary', 'custom_button_after_product_summary', 30 );

function custom_button_after_product_summary() {
  global $product;
  echo "<a href='".$product->add_to_cart_url()."'>add to cart</a>";
}

But if the product is a variation it doesn't work.

please suggest as what to do?

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

2 Answers2

1

I have revisited your code a bit, and added a 2nd hooked function for variable products:

// For Simple products
add_action( 'woocommerce_single_product_summary', 'second_button_after_product_summary', 30 );
function second_button_after_product_summary() {
    global $product;

    if( ! $product->is_type( 'variable' ) )
        echo '<button type="submit" name="add-to-cart" value="'. esc_attr( $product->get_id() ).'" class="single_add_to_cart_button button alt">'. esc_html( $product->single_add_to_cart_text() ).'</button>';
}

// For Variable products
add_action( 'woocommerce_single_variation', 'second_button_single_variation', 30 );
function second_button_single_variation() {
    global $product;

    echo '<br>
        <button type="submit" class="single_add_to_cart_button button alt">'. esc_html( $product->single_add_to_cart_text() ).'</button>';
}

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

You will get this on variable products:

enter image description here

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • 1
    i followed your code though it outputs the second button when clicked it doesnt add the product in the cart – mohammad imran Nov 14 '17 at 16:28
  • Button won't work because its missing action attribute. Just add action that returns the permalink for the product. `action="'. esc_url( apply_filters( 'woocommerce_add_to_cart_form_action', $product->get_permalink() ) ); .' "` – Poornamith Jan 03 '22 at 10:57
0

The answer @LoicTheAztec provided is correct but its missing the action attribute for the button click event. Here's the corrected code with the action attribute.

// For Simple products
add_action( 'woocommerce_single_product_summary', 'second_button_after_product_summary', 30 );
function second_button_after_product_summary() {
    global $product;

    if( ! $product->is_type( 'variable' ) )
        echo '<button type="submit" name="add-to-cart" value="'. esc_attr( $product->get_id() ).'" action="'.esc_url( apply_filters( 'woocommerce_add_to_cart_form_action', $product->get_permalink() ) ).'" class="single_add_to_cart_button button alt">'. esc_html( $product->single_add_to_cart_text() ).'</button>';
}

If you are using external products or variation items add the action attribute appropriately. Please refer "plugins/woocommerce/templates/single-product/add-to-cart"

Poornamith
  • 184
  • 3
  • 7