I need to redirect all traffic on my WordPress site to the homepage if not requested by AJAX, but I need to use the requested path after redirect.
I have redirection working via wp_redirect php and a template_redirect hook, however I can't read the REQUEST_URI to save it via cookie or header or anything.
As soon as wp_redirect is called it seemingly prevents me from ever reading the details of the request, pre redirect. Comment out the wp_redirect and it reads just fine.
Is there something I'm missing here, or a better way to go about it? I have a one page site that is loading content via AJAX.
add_action('template_redirect', 'pass_along_request_uri', 1);
function pass_along_request_uri() {
// $_SERVER['REQUEST_URI'] is the path as expected only if the future wp_redirect is not called...
}
add_action('template_redirect', 'redirect_to_homepage', 10);
function redirect_to_homepage() {
if (!is_front_page() && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')) {
wp_redirect(home_url(), 301);
exit;
}
}
EDIT; Only had 2 functions for testing, since logging $_SERVER['REQUEST_URI'] wasn't making sense to me. Thinking if I put the log at priority 1, it should be logged BEFORE the redirect happens with the priority 10 function.
However it doesn't. Doesn't matter when or where it seems, calling wp_redirect seemingly clears the original request data.
function console_log($output, $with_script_tags = true) {
$js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) .
');';
if ($with_script_tags) {
$js_code = '<script>' . $js_code . '</script>';
}
echo $js_code;
}
console_log($_SERVER['REQUEST_URI']);
Logs say "/path/to/page" when not calling wp_redirect, once wp_redirect is in the chain it only spits out "/" (the redirected path).
I'm thinking it has something to do with how actions are queued up with add_action? I don't know WordPress well unfortunately.
Thanks!
CodePudding user response:
Your mistake here was the way you are actually logging this.
The console.log(...)
executes on the client side - but there it can't log while you are doing your redirect elsewhere (you can not send output for the browser to interpret, like your script element, and redirect at the same time.)
What you are seeing is the result of that same logging code, executed via the request after your redirect.
Easiest way to achieve what you want, would probably be to stick the REQUEST_URI value into a session. You might have to start one then for that purpose, because WP does not use a "traditional" session by default.