Solution:
I have divided my answer into 3 parts. The intention is to add a copy of the existing add to cart button with 1 difference, and we will use that difference for the redirect.
Step 1) Adding the (copy) of the add to cart button can be done by adjusting/overwriting the template file, however it can also be done by using the available hooks in the template file, for example the woocommerce_after_add_to_cart_button
hook
// Add new/extra button
function action_woocommerce_after_add_to_cart_button() {
global $product;
// Button text
$button_text = __( 'My new text', 'woocommerce' );
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Simple products
if ( $product->is_type( 'simple' ) ) {
echo '<button type="submit" name="add-to-cart" value="'. esc_attr( $product->get_id() ) . '" class="single_add_to_cart_button button alt custom_redirect_button">' . $button_text . '</button>';
// Variable products
} elseif( $product->is_type( 'variable' ) ) {
echo '<button type="submit" class="single_add_to_cart_button button alt custom_redirect_button">' . $button_text . '</button>';
}
}
}
add_action( 'woocommerce_after_add_to_cart_button', 'action_woocommerce_after_add_to_cart_button', 10 );
This adds a copy of the existing add to cart button for simple and variable products but with 1 difference. Namely: when the button is clicked, a hidden input field is added via jQuery (step 2).
Step 2) This is the code to add the hidden input field with a certain value. I added the jQuery via an action hook but this can just as well be included in an external js file.
// Add jQuery to footer
function action_wp_footer() {
// Only on single product page
if ( is_product() ) {
?>
<script type="text/javascript">
jQuery( function($) {
// Add to cart button or custom button is clicked
$( document ).on( 'click', '.custom_redirect_button', function () {
// NOT disabled
if ( ! $( this ).hasClass( 'disabled' ) ) {
// Add hidden input field after
$( this ).after( '<input type="hidden" name="custom-redirect" value="my-value" />' );
}
});
});
</script>
<?php
}
}
add_action( 'wp_footer', 'action_wp_footer', 10 );
Step 3) Get the value from the hidden input field and when it matches, then it is our custom button and we apply our own url.
// Redirect
function filter_woocommerce_add_to_cart_redirect( $redirect_url, $product ) {
// If value isset
if ( isset( $_REQUEST['custom-redirect'] ) ) {
// If equal to
if ( $_REQUEST['custom-redirect'] == 'my-value' ) {
// URL to redirect to (1 is the page ID here)
$redirect_url = get_permalink( 1 );
}
}
return $redirect_url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'filter_woocommerce_add_to_cart_redirect', 10, 2 );