WooCommerce单个商品页加购后跳转结账功能异常问题
Hey there, let's tackle this issue—you mentioned your redirect works without the page condition, but breaks when you add the check for single simple product pages (even though your echo "it works" confirms the condition is triggering). Here's what's going on and how to fix it:
Common Reasons the Redirect Fails
Most likely, you're either using the wrong approach to handle the redirect (like direct wp_redirect() without proper context) or not leveraging WooCommerce's built-in filter designed exactly for this scenario. When you add a product to cart, WooCommerce uses the woocommerce_add_to_cart_redirect filter to determine where to send the user—this handles both standard page loads and AJAX add-to-cart actions, which is probably where your original code fell short.
Working Code Solution
Replace your existing code with this, which uses the correct filter and properly checks for your conditions:
add_filter( 'woocommerce_add_to_cart_redirect', 'redirect_to_checkout_for_simple_single_product', 999 ); function redirect_to_checkout_for_simple_single_product( $default_redirect ) { // Verify we're on a single product page if ( is_product() ) { $current_product = wc_get_product( get_the_ID() ); // Check if the product is a simple type if ( $current_product && $current_product->is_type( 'simple' ) ) { echo "it works"; // Keep your test echo to confirm condition hits // Override the redirect URL to the checkout page return wc_get_checkout_url(); } } // Fall back to the default redirect if conditions aren't met return $default_redirect; }
Why This Works
- Proper Filter Usage:
woocommerce_add_to_cart_redirectis the official WooCommerce filter for modifying add-to-cart redirects. Instead of forcing a redirect withwp_redirect(), we just return the desired URL—WooCommerce handles the rest, including AJAX scenarios. - Condition Validation: We first confirm we're on a single product page with
is_product(), then fetch the current product and check its type withis_type( 'simple' )(a reliable method for product type checks). - Priority Setting: The
999priority ensures our function runs after most other plugins/themes that might modify this filter, so our redirect doesn't get overridden.
Troubleshooting Tips
- If you still have issues, check if other plugins (like cart or checkout mods) are conflicting—temporarily disable them to test.
- Verify the product type is correctly detected: add
var_dump($current_product->get_type());inside the condition to make sure it returnssimple. - Remove the
echoonce you confirm the condition works—while it's useful for testing, it can interfere with AJAX responses.
内容的提问来源于stack exchange,提问作者Johanna Ferreira

