Skip to content

Instantly share code, notes, and snippets.

@aboglioli
Created August 5, 2016 19:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aboglioli/c1fa93f9f012f1251a0398fd19d7d6dd to your computer and use it in GitHub Desktop.
Save aboglioli/c1fa93f9f012f1251a0398fd19d7d6dd to your computer and use it in GitHub Desktop.
WooCommerce - Add a Buy button, when it's clicked the product will be added to your cart (as Add to Cart button) but you will be redirected to checkout page
<?php
// Add buy button on content-product listed in archive-product
function k_woocommerce_loop_add_to_cart_link($element, $product) {
// With variable products you have to select options
// You cannot redirect the user without having the options selected
if($product->product_type != 'variable' && $product->is_in_stock()) {
$element .= sprintf( '<a href="%s&buy=1" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>',
esc_url( $product->add_to_cart_url() ), // it adds 'buy=1' in parameters of URI
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
$product->is_purchasable() && $product->is_in_stock() ? 'buy_button' : '', // class
esc_attr( $product->product_type ),
esc_html('Comprar')
);
}
return $element;
}
add_filter('woocommerce_loop_add_to_cart_link', 'k_woocommerce_loop_add_to_cart_link', 10, 2);
// Redirect after buying clicking in Buy Button added above
function k_add_to_cart_redirect($url) {
if ( ! isset( $_REQUEST['add-to-cart'] ) || ! is_numeric( $_REQUEST['add-to-cart'] ) ) {
return $url;
}
// Your buy button add 'buy' parameter in URI, so you can know when you have to redirect the customer.
if(isset($_REQUEST['buy'])) {
return WC()->cart->get_cart_url();
}
return $url;
}
add_filter('woocommerce_add_to_cart_redirect', 'k_add_to_cart_redirect');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment