Sanad Cal
Sanad Cal

Reputation: 39

Redirect page if found some string in URL - Wordpress

I've created a function which suppose to redirect a user if /resources/ string is found in url of page he's trying to visit, but it's not working, can someone tell me what went wrong?

function redirect_collateral() {
if (strpos($_SERVER['REQUEST_URI'], "/resources/") !== false){
$url = $_SERVER['REQUEST_URI'];
$my_var = '';
$url = str_replace("/resources/", $my_var, $url );
header("Location: $url");

    }
}
add_action( 'init', 'redirect_collateral' );

Upvotes: 2

Views: 1545

Answers (1)

Krunal Bhimajiyani
Krunal Bhimajiyani

Reputation: 1179

  1. using str_contains():
function redirect_to_resources() {
    $uri = $_SERVER['REQUEST_URI'];

    if ( str_contains( $uri, '/resources/' ) ) {
        $my_var = '';
        $uri    = str_replace( '/resources/', $my_var, $uri );
        wp_safe_redirect( $uri );
      }
    }
add_action( 'template_redirect', 'redirect_to_resources' );
  1. using strpos():
function redirect_to_resources() {
    $uri = $_SERVER['REQUEST_URI'];

    if ( strpos( $uri, '/resources/' ) == true ) {
        $my_var = '';
        $uri    = str_replace( '/resources/', $my_var, $uri );
        wp_safe_redirect( $uri );
      }
    }
add_action( 'template_redirect', 'redirect_to_resources' );

Upvotes: 2

Related Questions