问题
Let me start by saying sorry that this title is somewhat vague. More specifically the title should be:
How to select the behavior of the "add to cart" button in a woocommerce Storefront theme (probably other themes as well) product archives page (aka shop page), such that it adds the item to the cart and then either stays on the shop page, or redirects to the cart.
But that is a long title...
回答1:
Redirected To Custom URL :
function my_custom_add_to_cart_redirect( $url ) {
$url = get_permalink( 1 ); // URL to redirect to (1 is the page ID here)
return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );
Redirect To Checkout :
function my_custom_add_to_cart_redirect( $url ) {
$url = WC()->cart->get_checkout_url();
return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );
Redirect For Certain Categories :
function my_custom_add_to_cart_redirect( $url ) {
if ( ! isset( $_REQUEST['add-to-cart'] ) || ! is_numeric( $_REQUEST['add-to-cart'] ) ) {
return $url;
}
$product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_REQUEST['add-to-cart'] ) );
// Only redirect products that have the 't-shirts' category
if ( has_term( 't-shirts', 'product_cat', $product_id ) ) {
$url = WC()->cart->get_checkout_url();
}
return $url;
}
add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );
回答2:
According to the official WooCommerce documentation
You will find in tab Products, section 'Display', the checkbox that does what you need: [ ] Redirect to the cart page after... Cheers.
回答3:
There may be a way to do this with woocommerce hooks and filters, but after spending some time trying to solve this problem that way, I stumbled across the easy solution which was not entirely obvious at first.
The Solution: Check or uncheck the "Enable AJAX add to cart buttons on archives" button under WooCommerce > Products > Display > Add to Cart Behavior section of the WP admin area.
That is apparently exactly what this button is for, however, it seems to me that the title of this checkbox is very misleading and is why it took me so long to find this solution. It should probably be changed to something more like: "Redirect to the cart page after successful addition from archive (shop)". The use of the acronym AJAX is unnecessary and very misleading as to the effect of the checkbox...
来源:https://stackoverflow.com/questions/35518938/how-to-change-the-redirect-of-the-add-to-cart-button-in-woocommerce-store