Plugin Directory

Changeset 3466005


Ignore:
Timestamp:
02/20/2026 06:53:53 PM (6 weeks ago)
Author:
pipdig
Message:

refactor

File:
1 edited

Legend:

Unmodified
Added
Removed
  • 404-to-homepage/trunk/404-to-homepage.php

    r3164829 r3466005  
    1111
    1212add_action('template_redirect', function() {
     13
     14    if (
     15        wp_doing_ajax() ||
     16        wp_doing_cron() ||
     17        is_admin() ||
     18        (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST) ||
     19        (defined('REST_REQUEST') && REST_REQUEST)
     20    ) return;
     21
     22    if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'HEAD') return;
     23
     24    if (empty($_SERVER['REQUEST_URI'])) return;
     25
     26    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
     27
     28    // Skip direct PHP file access
     29    if (substr($path, -4) === '.php') return;
     30
     31    // Skip sitemap
     32    if (strpos($path, 'sitemap.xml') !== false) return;
     33
     34    // Exclude uploads directory (cached)
     35    static $uploads_path = null;
     36    if ($uploads_path === null) {
     37        $u = wp_get_upload_dir();
     38        $uploads_path = parse_url($u['baseurl'], PHP_URL_PATH);
     39    }
     40
     41    if ($uploads_path && strpos($path, $uploads_path) === 0) return;
     42
     43    global $wp_query;
     44
     45    // Reliable low-level 404 check
     46    if (empty($wp_query) || empty($wp_query->is_404)) return;
     47
     48    // Prevent redirect loop if homepage ever 404s
     49    $home_path = untrailingslashit(parse_url(home_url('/'), PHP_URL_PATH));
     50    if (untrailingslashit($path) === $home_path) return;
     51
     52    wp_safe_redirect(home_url('/'), 301);
     53    die;
     54
     55}, PHP_INT_MAX);
     56
     57/*
     58add_action('template_redirect', function() {
    1359   
    1460    if (wp_doing_ajax() || wp_doing_cron() || is_admin() || (defined('XMLRPC_REQUEST') && XMLRPC_REQUEST)) return;
     
    2268   
    2369}, PHP_INT_MAX);
     70*/
Note: See TracChangeset for help on using the changeset viewer.