Learn how to create clean, permanent redirects between WordPress pages without losing admin access to edit them
Tools, Websites, WordPress customization

How to Redirect WordPress Pages Using Code Snippets

Learn how to create clean, permanent redirects between WordPress pages without losing admin access to edit them

Why Use Code-Based Redirects?

Code-based redirects offer several advantages:

  • SEO-friendly: 301 redirects preserve your page rankings
  • Clean: No need for redirect plugins
  • Maintainable: Easy to update when your site structure changes
  • Efficient: Minimal impact on site performance
  • Reliable: Works consistently across all WordPress themes

Important: Frontend-Only Implementation

To ensure you can always edit your pages in the WordPress admin, we’ll make these redirects work only on the frontend. This prevents you from getting locked out of the page editor.

The Complete Code (Recommended Method)

This is the definitive solution you should use. Copy and paste this code into Code Snippets plugin or your theme’s functions.php file:

/**
 * Custom Page Redirects
 * Frontend-only redirects that preserve admin access
 */
add_action('template_redirect', function() {
    // Safety check: only run on frontend
    if (is_admin()) {
        return;
    }
    
    // Single page redirect: 226 → 8968
    if (is_page(226)) {
        $redirect_url = get_permalink(8968);
        if ($redirect_url) {
            wp_redirect($redirect_url, 301);
            exit;
        }
    }
    
    // Multiple pages to one destination: 6504 and 6559 → 5443
    if (is_page(6504) || is_page(6559)) {
        $redirect_url = get_permalink(5443);
        if ($redirect_url) {
            wp_redirect($redirect_url, 301);
            exit;
        }
    }
    
    // Group redirect with array (cleaner for many pages)
    $group_pages = [6554, 7205, 7833, 6341, 7747, 7508, 963, 3188];
    if (is_page($group_pages)) {
        $redirect_url = get_permalink(8693);
        if ($redirect_url) {
            wp_redirect($redirect_url, 301);
            exit;
        }
    }
});

Understanding the Code Structure

Why Use template_redirect Hook?

add_action('template_redirect', function() {
    // Your redirect code here
});

The template_redirect hook executes at the perfect moment in WordPress lifecycle:

  • After WordPress determines which page to load
  • Before any HTML output is generated
  • Ensures redirects work reliably across all themes and plugins
  • Prevents “headers already sent” errors

The Admin Safety Check

if (is_admin()) {
    return;
}

This critical line ensures redirects only happen on the frontend. You’ll always be able to access and edit your pages in the WordPress admin panel, even if they’re redirected for visitors.

The Permalink Validation Check

$redirect_url = get_permalink(8968);
if ($redirect_url) {
    wp_redirect($redirect_url, 301);
    exit;
}

Why check if $redirect_url exists?

  • Prevents redirects if the destination page doesn’t exist
  • Avoids broken links if the target page is in trash
  • Returns false if the page ID is invalid
  • Protects against redirect errors

Using Arrays for Multiple Pages

$group_pages = [6554, 7205, 7833, 6341, 7747, 7508, 963, 3188];
if (is_page($group_pages)) {
    $redirect_url = get_permalink(8693);
    if ($redirect_url) {
        wp_redirect($redirect_url, 301);
        exit;
    }
}

Using an array is much cleaner than chaining multiple || conditions. WordPress is_page() function accepts arrays natively.

Step-by-Step Installation

Method 1: Using Code Snippets Plugin (Recommended)

  1. Install the Code Snippets plugin from WordPress repository
  2. Go to Snippets → Add New
  3. Give it a name like “Page Redirects”
  4. Paste the complete code above
  5. Select “Run snippet everywhere” (the is_admin() check handles frontend-only execution)
  6. Click Save Changes and Activate

Note: If your Code Snippets plugin has an option “Only run on site front-end”, you can select that and remove the if (is_admin()) return; line from the code.

Method 2: Adding to functions.php

  1. Go to Appearance → Theme File Editor
  2. Select functions.php from the right sidebar
  3. Scroll to the bottom of the file
  4. Paste the complete code above
  5. Click Update File
⚠️ Warning: Always backup your site before editing theme files directly. If you use a child theme, add the code to the child theme’s functions.php.

Customizing for Your Needs

Find Your Page IDs

To find a page ID in WordPress:

  1. Go to Pages → All Pages
  2. Hover over the page title
  3. Look at the URL in your browser’s status bar
  4. The number after post= is your page ID

Example: ...post.php?post=1979&action=edit → Page ID is 1979

Add a New Single Page Redirect

Add this code inside the template_redirect function, before the closing });

// Redirect page 101 to page 1979
if (is_page(101)) {
    $redirect_url = get_permalink(1979);
    if ($redirect_url) {
        wp_redirect($redirect_url, 301);
        exit;
    }
}

Replace 101 with your source page ID and 1979 with your destination page ID.

Add Multiple Pages to One Destination

// Redirect pages 100, 200, 300 to page 999
if (is_page(100) || is_page(200) || is_page(300)) {
    $redirect_url = get_permalink(999);
    if ($redirect_url) {
        wp_redirect($redirect_url, 301);
        exit;
    }
}

// OR using array method (cleaner):
$old_pages = [100, 200, 300];
if (is_page($old_pages)) {
    $redirect_url = get_permalink(999);
    if ($redirect_url) {
        wp_redirect($redirect_url, 301);
        exit;
    }
}

Alternative: Array-Based Redirect System

For managing many redirects, this approach is more maintainable:

/**
 * Array-Based Redirect System
 * Easy to maintain multiple one-to-one redirects
 */
add_action('template_redirect', function() {
    if (is_admin()) {
        return;
    }
    
    // Define all redirects as from => to pairs
    $redirects = [
        226 => 8968,   // Old about page → New about
        6504 => 5443,  // Old service A → New services
        6559 => 5443,  // Old service B → New services
        101 => 1979,   // Legacy page → Current page
    ];
    
    foreach ($redirects as $from => $to) {
        if (is_page($from)) {
            $redirect_url = get_permalink($to);
            if ($redirect_url) {
                wp_redirect($redirect_url, 301);
                exit;
            }
        }
    }
});

Benefits of this approach:

  • All redirects in one place
  • Easy to add/remove redirects
  • Clean and readable
  • Perfect for 10+ redirects

Testing Your Redirects

  1. Test the frontend redirect:
    • Open the old page URL in a new incognito/private browser window
    • Verify you’re automatically redirected to the new page
  2. Verify admin access:
    • Go to Pages → All Pages
    • Click “Edit” on the redirected page
    • Confirm you can still access the editor
  3. Check redirect status code:
    • Use a tool like httpstatus.io
    • Enter your old page URL
    • Verify it shows “301 Moved Permanently”
  4. Clear all caches:
    • Browser cache
    • WordPress cache plugin
    • Server cache (if applicable)

Understanding Redirect Types

301 Redirect – Permanent (Recommended)

wp_redirect($redirect_url, 301);
  • Tells search engines the page has moved permanently
  • Transfers SEO value (PageRank) to the new URL
  • Best for restructuring, consolidating content, or replacing old pages
  • Browsers and search engines may cache this redirect

302 Redirect – Temporary

wp_redirect($redirect_url, 302);
  • Indicates the redirect is temporary
  • Search engines keep the original URL indexed
  • Use for A/B testing, seasonal pages, or temporary maintenance
  • Change 301 to 302 in the code

Troubleshooting Common Issues

❌ Redirect Not Working?

  • Clear browser cache: 301 redirects are cached aggressively
  • Clear WordPress cache: Disable caching plugins temporarily
  • Check page IDs: Verify both source and destination IDs are correct
  • Test in incognito mode: Avoids cached redirects
  • Check if snippet is active: Go to Snippets and verify it’s enabled

❌ Can’t Access the Page Editor?

  • Verify the admin check: Make sure if (is_admin()) return; is at the top
  • Temporarily deactivate: Disable the code snippet to regain access
  • Check for syntax errors: A missing bracket can break the admin check

❌ Redirect Loop Error?

  • Self-redirect: Make sure you’re not redirecting a page to itself
  • Circular redirects: Page A → Page B → Page A creates a loop
  • Plugin conflicts: Another redirect plugin might be interfering
  • Check .htaccess: Server-level redirects might conflict

❌ “Headers Already Sent” Error?

  • Output before redirect: There’s content echoed before wp_redirect()
  • Check for whitespace: Extra spaces or newlines before <?php
  • Use template_redirect hook: This prevents the error

❌ Destination Page Returns 404?

  • Page doesn’t exist: Check if destination page ID is published
  • Page in trash: Restore the destination page
  • Incorrect ID: Verify the destination page ID is correct
  • Good news: The if ($redirect_url) check prevents this

Best Practices

✅ Do’s

  • Always test in staging first if you have a staging environment
  • Keep redirects organized with clear comments explaining each one
  • Use the permalink check if ($redirect_url) for safety
  • Document your redirects in a spreadsheet for reference
  • Monitor 404 errors to identify pages that need redirects
  • Use 301 for permanent changes to preserve SEO
  • Group similar redirects using arrays for better organization

❌ Don’ts

  • Don’t chain redirects: A → B → C loses SEO value and slows down page load
  • Don’t redirect forever: After 6-12 months, update internal links instead
  • Don’t redirect without testing: Always verify admin access is preserved
  • Don’t ignore 301 caching: Remember that browsers cache permanent redirects
  • Don’t forget the exit: Always include exit; after wp_redirect()

When to Update Internal Links

While redirects preserve SEO and user experience, they add a small performance cost. After implementing redirects:

  1. Search for internal links: Use a plugin like “Better Search Replace” to find old URLs
  2. Update navigation menus: Point menu items directly to new pages
  3. Fix widget links: Update any sidebar or footer links
  4. Update content links: Edit posts and pages to use new URLs
  5. Keep redirects active: For external backlinks and bookmarks

Monitoring and Maintenance

Regular Review Schedule

  • Monthly: Check redirect performance and server logs
  • Quarterly: Review which redirects are still needed
  • Annually: Clean up redirects that receive no traffic

Tools for Monitoring

  • Google Search Console: Monitor crawl errors and redirect chains
  • Google Analytics: Track traffic to redirected pages
  • Server logs: Identify which redirects are used most
  • Redirect checkers: Periodically verify redirect status codes

Conclusion

Code-based page redirects give you complete control over your WordPress site’s URL structure while maintaining SEO value and user experience. By following the structure outlined in this guide, you ensure:

  • ✅ Redirects work reliably across all themes and plugins
  • ✅ Admin access is always preserved for editing
  • ✅ Destination pages are validated before redirecting
  • ✅ Code is clean, maintainable, and well-organized
  • ✅ SEO value is preserved with proper 301 redirects

🎯 Quick Reference: The Perfect Redirect

add_action('template_redirect', function() {
    if (is_admin()) {
        return;
    }
    
    if (is_page(SOURCE_ID)) {
        $redirect_url = get_permalink(DESTINATION_ID);
        if ($redirect_url) {
            wp_redirect($redirect_url, 301);
            exit;
        }
    }
});

Remember: Always use template_redirect hook + admin check + permalink validation for bulletproof redirects.

Keep your redirect code clean, well-commented, and regularly reviewed to maintain optimal site performance and SEO health.

Need help with this solution or looking for custom development?

Visit my Stay In Touch page to connect and discuss your project. Discover a range of web development services and specialized WordPress solutions tailored to your needs. Let's work together to enhance your digital presence.