Home > Mobile >  Safest way to get current page in Wordpress through $_SERVER
Safest way to get current page in Wordpress through $_SERVER

Time:09-20

I need to determine a redirect to another page very early in WP loading, specifically within init hook. For anyone familiar, at init hook, no global variables, like $pagenow or $wpdb, are set or initialized yet. So I have to rely on $_SERVER superglobal to determine the current page. But which of the various $_SERVER variables is the safest to use? I'm reading that some don't exist at specific environments. I checked mine, and I got the following results...

  • ['REQUEST_URI'] <- current page, also contains the query string, ie. /current-page/?some-query-string
  • ['REDIRECT_URL'] <- clean current page, ie. /current-page/
  • ['SCRIPT_URI'] <- full URL, doesn't contain the query string, ie. https://my-domain.tld/current-page/
  • ['SCRIPT_URL'] <- clean current page, ie. /current-page/
  • ['REDIRECT_SCRIPT_URI'] <- full URL, doesn't contain the query string, ie. https://my-domain.tld/current-page/
  • ['REDIRECT_SCRIPT_URL'] <- clean current page, ie. /current-page/

What I need is the current page, free of query-strings, etc, so anything like REDIRECT_URL, SCRIPT_URL, REDIRECT_SCRIPT_URL are fine, but which of the three is the safest to use?

Thank you in advance for any answer.

CodePudding user response:

If you're trying to redirect a page to another page then you should use template_redirect action then you can check your page with the function is_page and then using wp_safe_redirect you can redirect your page to another page/url.

  • Related