Woocommerce:根据用户名登录重定向失效问题求助
Fix: WooCommerce Login Redirect for Specific Username Not Working
Hey there, let's break down why your redirect code isn't working and fix it up:
First, I spotted two key issues in your code that are blocking it from working correctly:
- Syntax Error: There's an extra closing curly brace
}at the very end of your snippet. This is a PHP parsing error that stops the entire function from loading properly. - Incorrect URL Method for Product Categories:
get_page_by_path()is built to fetch WordPress Pages (thepagepost type), but product categories are a custom taxonomy (product_cat). Using this function won't pull the right URL for your category—you need taxonomy-specific tools instead.
Here's the corrected, working code:
function wc_custom_user_redirect( $redirect, $user ) { // Get the user's login username $username = $user->user_login; // Handle redirect rules based on username switch ( $username ) { case 'rosinarep': // Fetch the "gifting" product category and its URL $gifting_category = get_term_by( 'slug', 'gifting', 'product_cat' ); if ( $gifting_category ) { $redirect = get_term_link( $gifting_category ); } break; default: // Fallback: redirect to the previous page or home if no referrer exists $redirect = wp_get_referer() ? wp_get_referer() : home_url(); } return $redirect; } add_filter( 'woocommerce_login_redirect', 'wc_custom_user_redirect', 10, 2 );
Key Fixes Explained:
- Removed the extra
}at the end to resolve the syntax error. - Swapped
get_page_by_path()forget_term_by()+get_term_link(): This is the proper way to get a product category's URL, since product categories are taxonomies, not standard pages. - Added a check to confirm the
giftingcategory exists before setting the redirect—this prevents errors if the category is ever deleted or renamed.
Quick Troubleshooting Tips:
- Double-check your theme's
functions.phpfor other syntax errors (even a missing semicolon can break all custom code). - Clear your browser cache and any WordPress caching plugins—old redirect rules can get stuck in cache.
- Ensure the username
rosinarepis an exact match (it's case-sensitive, soRosinarepwon't trigger the redirect).
内容的提问来源于stack exchange,提问作者Rosie
相关产品推荐
相关产品推荐

