Skip to content

Instantly share code, notes, and snippets.

@salvatorecapolupo
Created September 3, 2026 16:31
Show Gist options
  • Select an option

  • Save salvatorecapolupo/0d8c51efab55d913c893ab7e2e5493eb to your computer and use it in GitHub Desktop.

Select an option

Save salvatorecapolupo/0d8c51efab55d913c893ab7e2e5493eb to your computer and use it in GitHub Desktop.
Redirect 302 pagine 4XX verso pagina di ricerca con primi due termini usati nell'URL originale per massima pertinenza.
<?PHP
/**
* Redirect di tutti gli errori HTTP 4XX verso la ricerca WordPress.
*
* Esempio:
* /scarpe-running-uomo/nike-air-max/qualcosa/
*
* diventa:
* /?s=scarpe+running+uomo
*
* Redirect: 302
*/
class Redirect_4xx_To_Search {
private $status_code = null;
public function __construct() {
// Memorizza il codice HTTP che WordPress sta per inviare.
add_filter('status_header', [$this, 'capture_status'], 10, 2);
// Esegue il redirect quando WordPress ha determinato la pagina.
add_action('template_redirect', [$this, 'maybe_redirect'], 20);
}
/**
* Cattura il codice HTTP senza modificarlo.
*/
public function capture_status($status_header, $code) {
$this->status_code = (int) $code;
return $status_header;
}
/**
* Redirect per qualsiasi errore 4XX.
*/
public function maybe_redirect() {
// Se conosciamo il codice HTTP, deve essere un 4XX.
if (
$this->status_code !== null &&
($this->status_code < 400 || $this->status_code >= 500)
) {
return;
}
// Se il codice non è stato catturato, non fare nulla.
if ($this->status_code === null) {
return;
}
// Evita admin, AJAX, cron, feed e REST API.
if (
is_admin() ||
wp_doing_ajax() ||
wp_doing_cron() ||
is_feed() ||
(defined('REST_REQUEST') && REST_REQUEST)
) {
return;
}
// Recupera il path dell'URL richiesto.
$request_uri = $_SERVER['REQUEST_URI'] ?? '';
$path = wp_parse_url($request_uri, PHP_URL_PATH);
if (!$path) {
return;
}
// Divide l'URL in segmenti.
$segments = array_values(
array_filter(explode('/', trim($path, '/')))
);
if (empty($segments)) {
return;
}
// Prende massimo i primi 3 segmenti.
$segments = array_slice($segments, 0, mt_rand(2,3));
// Trasforma ogni segmento in parole.
$words = [];
foreach ($segments as $segment) {
// Rimuove eventuale estensione (.html, .php, ecc.).
$segment = preg_replace('/\.[a-z0-9]{1,5}$/i', '', $segment);
// Divide su -, _, + e spazi.
$parts = preg_split(
'/[-_+\s]+/',
$segment,
-1,
PREG_SPLIT_NO_EMPTY
);
if ($parts) {
$words = array_merge($words, $parts);
}
}
if (empty($words)) {
return;
}
// Massimo 2 parole complessive.
$words = array_slice($words, 0, 2);
// Costruisce la ricerca.
$query = implode(' ', $words);
// URL della ricerca WordPress.
$search_url = home_url('/?s=' . urlencode($query));
// Redirect temporaneo 302.
wp_safe_redirect($search_url, 302);
exit;
}
}
new Redirect_4xx_To_Search();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment