Skip to content

Instantly share code, notes, and snippets.

@rabbitinblack
Last active August 29, 2015 14:06
Show Gist options
  • Save rabbitinblack/7a9888fdf1c6999ca063 to your computer and use it in GitHub Desktop.
Save rabbitinblack/7a9888fdf1c6999ca063 to your computer and use it in GitHub Desktop.
Modified WooCommerce Add to cart Button Auto add product to cart
<?php
/**
* Loop Add to Cart
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.1.0
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $product;
echo (sprintf( '<a href="%s" class="button">%s</a>', esc_url( get_permalink( $product->id )), 'View Details' ));
if( $product->has_child() ) {
$selected_attributes = $product->get_variation_default_attributes();
$title = array_keys($selected_attributes);
$available_variations = $product->get_available_variations();
foreach ( $available_variations as $this_variation ) {
$matchcheck = 0;
for ($i=0; $i < sizeof($title) ; $i++) {
if ( $this_variation['attributes']['attribute_' . $title[$i]] == $selected_attributes[$title[$i]] ) {
$matchcheck = $matchcheck + 1;
}
}
if ( sizeof($title) == $matchcheck) {
$variation_id = $this_variation['variation_id'];
}
}
}
?>
<?php if ( ! empty( $selected_attributes ) ) : ?>
<form class="variations_form cart" method="post" enctype='multipart/form-data'>
<?php for ($i=0; $i < sizeof($title) ; $i++) { ?>
<input type="hidden" id="<?php echo $title[$i]; ?>" name="attribute_<?php echo $title[$i]; ?>" value="<?php echo $selected_attributes[$title[$i]]; ?>">
<?php } ?>
<input type="hidden" name="quantity" value="1" title="Qty">
<button type="submit" class="single_add_to_cart_button button alt"><?php echo $product->single_add_to_cart_text(); ?></button>
<input type="hidden" name="add-to-cart" value="<?php echo $product->id; ?>" />
<input type="hidden" name="product_id" value="<?php echo $product->id; ?>" />
<input type="hidden" name="variation_id" value="<?php echo $variation_id; ?>" />
</form>
<?php else :
echo apply_filters( 'woocommerce_loop_add_to_cart_link',
sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" class="button %s product_type_%s">%s</a>',
esc_url( $product->add_to_cart_url() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
$product->is_purchasable() ? 'add_to_cart_button' : '',
esc_attr( $product->product_type ),
esc_html( $product->single_add_to_cart_text() )
),
$product );
endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment