Skip to content

Instantly share code, notes, and snippets.

@raazon
Last active December 13, 2020 08:03
Show Gist options
  • Save raazon/b4136fbdee1ebb203a800bd7dd0e7d06 to your computer and use it in GitHub Desktop.
Save raazon/b4136fbdee1ebb203a800bd7dd0e7d06 to your computer and use it in GitHub Desktop.
Redirect if specific slug found in URL PHP / Redirect if specific slug not found in URL PHP
<?php
/*
* Redirect if specific slug "hello-world OR hello-regex" not found in URL
*/
add_action('template_redirect', 'ic_icredirection');
function ic_icredirection()
{
if (!is_user_logged_in()) {
$regex = '/^(?:(?!\/(?:hello-world|hello-regex)(?:\/|$)).)*$/m';
$str = home_url($_SERVER['REQUEST_URI']);
if (preg_match_all($regex, $str, $matches, PREG_SET_ORDER, 0)) {
wp_redirect(home_url());
}
}
}
/*
* Redirect if specific slug "hello-world OR hello-regex" found in URL
*/
add_action('template_redirect', 'ic_icredirection');
function ic_icredirection()
{
if (!is_user_logged_in()) {
$regex = '/(http(s)?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w- ;,.\/?%&=]*)?(hello-world|hello-regex)/m';
$str = home_url($_SERVER['REQUEST_URI']);
if (preg_match_all($regex, $str, $matches, PREG_SET_ORDER, 0)) {
wp_redirect(home_url());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment