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

基于Cookie实现WordPress品牌页面自动跳转的问题求助

Hey there, let's work through those cookie redirect issues you're facing—they're super common with WordPress hook timing and conditional logic, so we'll fix this step by step.

First, Let's Diagnose Your Existing Problems

Let's break down why each code version broke:

  • White screen with initial redirect: Your wp_redirect was triggering, but you didn't check if you were already on the target brand page (so it tried to redirect even when you were there, causing a broken load). Also, $pagename isn't a global variable you can use directly without defining it first.
  • Site crash with standalone redirect code: You placed raw PHP logic directly in functions.php without wrapping it in a hook or function—WordPress didn't know when to run it, leading to fatal errors.
  • Too many redirects: Your conditional logic was repeating $pagename != 'home' in every elseif, and again, you didn't exclude the target brand pages from the redirect check. So if your cookie was set to brand_2, it kept trying to redirect to /brand2 even when you were already there, creating an infinite loop.

Here's the Fixed, Complete Solution

We'll rewrite both the cookie setup and redirect logic to handle multi-brand cases properly, with safeguards against loops and errors.

1. Cookie Setup Function (Updated)

This will only set the cookie when a user visits a brand page, and won't auto-set a default cookie on first visit (so users see your brand selection page first):

function brand_cookies() {
    // Define your brand page slugs and their corresponding cookie values
    $brands = [
        'brand1' => 'brand_1',
        'brand2' => 'brand_2',
        'brand3' => 'brand_3'
    ];

    // Loop through brands to set cookie when user visits the brand page
    foreach ($brands as $page_slug => $cookie_value) {
        if (is_page($page_slug)) {
            // Set secure, long-lived cookie (adjust expiry as needed)
            setcookie(
                'brands',
                $cookie_value,
                time() + (3600 * 24 * 365 * 3), // 3 years expiry
                SITECOOKIEPATH,
                COOKIE_DOMAIN,
                is_ssl(), // Use secure flag if site is HTTPS
                true // HttpOnly flag for security
            );
            break; // Exit loop once we match the current brand page
        }
    }
}
add_action('wp', 'brand_cookies');

2. Redirect Function (Fixed to Avoid Loops & Errors)

This will check for the cookie, skip redirects if we're already on the target brand page, and only trigger when needed:

function brand_redirect() {
    // Get the current page slug (proper way to access it in WordPress)
    global $post;
    $current_page_slug = isset($post) ? $post->post_name : '';

    // Define brand mapping: cookie value => page slug
    $brand_map = [
        'brand_1' => 'brand1',
        'brand_2' => 'brand2',
        'brand_3' => 'brand3'
    ];

    // Skip redirect if:
    // - We're already on a brand page
    // - No cookie is set (user is visiting for the first time)
    // - We're on the home/brand selection page
    if (in_array($current_page_slug, $brand_map) || !isset($_COOKIE['brands']) || $current_page_slug === 'home') {
        return;
    }

    // Get the target page slug from the cookie
    $target_slug = $brand_map[$_COOKIE['brands']] ?? '';

    // If we have a valid target, redirect to the brand page
    if (!empty($target_slug)) {
        $target_url = get_permalink(get_page_by_path($target_slug));
        wp_redirect($target_url);
        exit; // Always exit after wp_redirect to stop further execution
    }
}
add_action('template_redirect', 'brand_redirect');

Key Fixes Explained

  • No infinite loops: We check if we're already on the target brand page before redirecting, so the browser doesn't get stuck in a loop.
  • Proper WordPress variables: We use global $post to safely get the current page slug instead of relying on undefined variables like $pagename.
  • Secure cookie settings: We added is_ssl() to toggle the secure flag based on your site's HTTPS status, and kept the HttpOnly flag for security.
  • Fallback checks: We use the null coalescing operator (??) to handle cases where the cookie value doesn't match any brand, preventing errors.

How to Test

  1. Clear your browser cookies for the site first.
  2. Visit the home page—you'll see your brand selection options as expected.
  3. Click a brand page (e.g., /brand2), which sets the cookie.
  4. Close the browser or visit any other non-brand page—you'll automatically redirect to the brand page you selected.
  5. Visit the brand page directly—no redirect happens, so no loops.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:30:16