Created
September 21, 2021 17:18
-
-
Save kingkool68/f9b627baf1113215081f7df720ea18c2 to your computer and use it in GitHub Desktop.
Make WordPress respond to a request for a URL that doesn't actually exist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Make WordPress respond to a request for a URL that doesn't actually exist | |
*/ | |
if ( ! function_exists( 'str_starts_with' ) ) { | |
/** | |
* Polyfill for PHP 8's str_starts_with | |
* | |
* @link https://php.watch/versions/8.0/str_starts_with-str_ends_with | |
* | |
* @param string $haystack The string to search in. | |
* @param string $needle The substring to search for in the haystack. | |
* @return boolean | |
*/ | |
function str_starts_with( string $haystack, string $needle ): bool { | |
return \strncmp( $haystack, $needle, \strlen( $needle ) ) === 0; | |
} | |
} | |
if ( ! function_exists( 'str_contains' ) ) { | |
/** | |
* Polyfill for PHP8's str_contains | |
* | |
* @link https://php.watch/versions/8.0/str_contains | |
* | |
* @param string $haystack The string to search in. | |
* @param string $needle The substring to search for in the haystack. | |
* @return boolean | |
*/ | |
function str_contains( string $haystack, string $needle ): bool { | |
return '' === $needle || false !== strpos( $haystack, $needle ); | |
} | |
} | |
/** | |
* Get the current URL of the request as detected by WordPress | |
*/ | |
function helper_to_get_current_url() { | |
global $wp; | |
$current_url = home_url( add_query_arg( array(), $wp->request ) ); | |
$current_url = trailingslashit( $current_url ); | |
if ( ! empty( $_GET ) ) { | |
$current_url = add_query_arg( $_GET, $current_url ); | |
} | |
return $current_url; | |
} | |
add_action( 'template_redirect', 'action_template_redirect', 100 ); | |
function action_template_redirect() { | |
// If WordPress determines a page for this URL actually exists, then bail and show that page | |
if ( ! is_404() ) { | |
return; | |
} | |
$current_url = helper_to_get_current_url(); | |
if ( str_contains( $current_url, '/invite' ) ) { | |
$redirect_url = ''; | |
// Do something to construct your redirect URL | |
wp_redirect( $redirect_url, $status = 301 ); | |
die(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment