Using WordPress ‘redirect_guess_404_permalink()’ PHP function

The redirect_guess_404_permalink() WordPress PHP function attempts to guess the correct URL for a 404 request based on query variables.

Usage

$redirect_url = redirect_guess_404_permalink();

Parameters

  • None

More information

See WordPress Developer Resources: redirect_guess_404_permalink

Examples

Redirect to Guessed URL

Detect when a 404 error occurs and redirect to the guessed URL.

function my_404_guess_redirect() {
  if (is_404()) {
    $redirect_url = redirect_guess_404_permalink();
    if ($redirect_url) {
      wp_redirect($redirect_url, 301);
      exit;
    }
  }
}
add_action('template_redirect', 'my_404_guess_redirect');

Custom 404 Template

Use the guessed URL in a custom 404 template to suggest a possible correct link.

In your theme’s 404.php:

$guessed_url = redirect_guess_404_permalink();

if ($guessed_url) {
  echo "Did you mean: <a href='{$guessed_url}'>{$guessed_url}</a>?";
}

Custom 404 Message

Display a custom 404 message if the guessed URL is found.

function my_custom_404_message() {
  $guessed_url = redirect_guess_404_permalink();
  if ($guessed_url) {
    echo "Oops! It looks like the page you're looking for may have moved. Try visiting <a href='{$guessed_url}'>{$guessed_url}</a> instead.";
  } else {
    echo "We're sorry, but the page you're looking for cannot be found.";
  }
}
add_action('wp_404_error_message', 'my_custom_404_message');

Logging 404 Errors

Log 404 errors with guessed URL in a custom log file.

function log_404_errors() {
  if (is_404()) {
    $guessed_url = redirect_guess_404_permalink();
    $current_url = home_url(add_query_arg(array(), $wp->request));
    $log_message = "404 Error: {$current_url} | Guessed URL: {$guessed_url}" . PHP_EOL;
    error_log($log_message, 3, "/path/to/your/logfile.log");
  }
}
add_action('template_redirect', 'log_404_errors');

Redirect 404 Errors to a Specific Page

Redirect 404 errors to a specific page if the guessed URL is not found.

function redirect_404_to_specific_page() {
  if (is_404()) {
    $guessed_url = redirect_guess_404_permalink();
    if (!$guessed_url) {
      wp_redirect(home_url('/your-specific-page/'), 301);
      exit;
    }
  }
}
add_action('template_redirect', 'redirect_404_to_specific_page');