Updated (the right custom url when it's a defined product category)
Using a custom function hooked in woocommerce_add_to_cart_redirect
filter hook, that will redirect customer when a product is added to cart (for defined product category(ies)):
add_filter( 'woocommerce_add_to_cart_redirect', 'conditional_add_to_cart_redirection', 99, 1 );
function conditional_add_to_cart_redirection( $url ) {
// ==> HERE define your product category or categories in the array
$category = array( 'clothing', 'music' );
if ( ! isset( $_REQUEST['add-to-cart'] ) ) return $url; // Very important!
// When it's available (on add to cart click), get the product ID
$product_id = absint( $_REQUEST['add-to-cart'] );
// Get the custom url from product post meta data
$custom_url = get_post_meta( $product_id, '_rv_woo_product_custom_redirect_url', true );
// Exit to normal, If the custom URL redirection is not set in the product
if( empty( $custom_url ) ) return $url;
// Custom redirection only for your defined product category(ies)
if( has_term( $category, 'product_cat', $product_id ) ){
// Clear add to cart notice (with the cart link).
wc_clear_notices();
$url = $custom_url; // Updated here
}
return $url;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Code is tested on Woocommerce 3+ and works
Add to cart redirection will not work with ajax add to cart on shop and archives pages. So you will have to choose between that 2 options for shop and archives pages:
- Disable ajax add-to-cart on shop and archives pages ( WC settings > Products > Display ).
- Add the following code to replace the add to cart button, by a button linked to the product:
This 2nd option seems to be the best (as this is conditional on some products only):
// Conditionally changing add to cart button link and text on shop and archives
add_filter( 'woocommerce_loop_add_to_cart_link', 'replacing_add_to_cart_button', 10, 2 );
function replacing_add_to_cart_button( $button, $product ) {
if( $product->is_type( 'variable-subscription' ) || $product->is_type( 'variable' ) ) return $button;
// ==> HERE define your product category or categories in the array
$category = array( 'clothing', 'music' );
// Check that the custom url from product post meta data is not empty
$custom_url = get_post_meta( $post->ID, '_rv_woo_product_custom_redirect_url', true );
if( empty( $custom_url ) ) return $button;
// Check if the current product has a defined product category(ies)
if( ! has_term( $category, 'product_cat', $post->ID ) ) return $button;
$button_text = __( 'View product', 'woocommerce' );
$button = '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
return $button;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Code is tested on Woocommerce 3+ and works