简体   繁体   中英

Adding Extra Add to cart button below product summary in Woocommerce

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?

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:

在此处输入图片说明

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM