Change Add to Cart Button in WooCommerc
If you want to redirect your customers to a third-party checkout URL after the customer clicks on the add to cart button from your single product page, shop page, or archive page.
You have to change the default add to cart button on the single product page and product loops.
For example, you want to redirect your all products to the third-party URL: https://example.com and you also have to pass some parameters like product URL, product title, and product image.
To achieve this you just have to read and put the given hooks to your theme’s functions.php file.
// this hook will change add to cart button on single product page
add_action( 'woocommerce_single_product_summary', 'add_to_cart_button_woocommerce_', 40 );
function add_to_cart_button_woocommerce_() {
global $product;
$product_link = $product->get_permalink();
$product_name = $product->get_name();
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $product->get_id() ), 'single-post-thumbnail' );
$product_image = (!empty($image))?$image[0]:'';
$url = 'https://example.com/?product_link='.$product_link.'&product_name='.$product_name.'&product_image='.$product_image;
$html = sprintf( '<a href="%s" class="single_add_to_cart_button button alt">%s</a>', $url, __("Add to cart", "woocommerce") );
echo '<style>.single-product div.product form.cart {
display: none !important;
}</style>'; // Removing existing add to cart button from single product page
echo $html;
}
// This hook will change add to cart button in every product loop
add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_woocommerce_loop_add_to_cart_link', 10, 2 );
function quantity_inputs_for_woocommerce_loop_add_to_cart_link( $html, $product ) {
$product_link = $product->get_permalink();
$product_name = $product->get_name();
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $product->get_id() ), 'single-post-thumbnail' );
$product_image = (!empty($image))?$image[0]:'';
$url = 'https://example.com/?product_link='.$product_link.'&product_name='.$product_name.'&product_image='.$product_image;
$html = sprintf( '<a href="%s" class="button product_type_simple add_to_cart_button ajax_add_to_cart">%s</a>', $url, __("Add to cart", "woocommerce") );
return $html;
}
You can also apply some conditions in these hooks according to your need like if you want to change this add to cart button for a specific product id etc…