You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 (the page post 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:

  1. Removed the extra } at the end to resolve the syntax error.
  2. Swapped get_page_by_path() for get_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.
  3. Added a check to confirm the gifting category 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.php for 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 rosinarep is an exact match (it's case-sensitive, so Rosinarep won't trigger the redirect).

内容的提问来源于stack exchange,提问作者Rosie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:15:00