skip to Main Content

I need to add several checks when user manually inputs URL with params on my site.

For example, if user types mysite.com/?random=text I want to redirect him to custom page (let’s imagine that I forbid using var random and I want users to be redirected in such cases).

How can I do this in WordPress?

2

Answers


  1. You can do that with JavaScript, it’s not really related to WordPress:

    window.onload = function() {
        const queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        const random = urlParams.get('random')
        if(random === "text") {
            window.location.href = "https://google.com/";
        }
    }
    

    It’s also possible with php, but I think JS is the easiest way.

    Login or Signup to reply.
  2. add_action('parse_request', 'my_custom_url_handler');
    function my_custom_url_handler() {
       $redirect_url = 'https://google.com/';
    
       if ( isset( $_GET['random' ]) && $_GET['random'] === 'text' && $_SERVER["REQUEST_URI"] == '/' ) {
          wp_redirect( $redirect_url , 404 );
          exit;
       }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search