Home > OS >  How to process GET requests in WordPress?
How to process GET requests in WordPress?

Time:06-14

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?

CodePudding user response:

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.

CodePudding user response:

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;
   }
}
  • Related