I don't need a frontend on the WP site. All visitors will be redirected to an external url where my frontend app lives.
I now have the following code in the root of my theme functions.php:
if ( ! is_admin() ) {
wp_redirect( '', 200 );
exit;
}
Unfortunately this runs before the plugins needed to set up the rest api have run.
Where should I place this code to get it right?
Warning!
See answers(s) below.Found a solution myself:
add_action( 'wp_loaded', function () {
// check if there is a 'wp-json' URI part
if (! strpos($_SERVER['REQUEST_URI'], 'wp-json')) {
// No rest api request. Now check if we are on frontend
if ( ! is_admin() ) {
// We are on frontend: redirect now
wp_redirect( '', 200 );
exit();
}
}
});
The above code works fine (tested) if put in a plugin file.
The above code does not work (tested) when put in the root of theme functions.php
file.
I don't need a frontend on the WP site. All visitors will be redirected to an external url where my frontend app lives.
I now have the following code in the root of my theme functions.php:
if ( ! is_admin() ) {
wp_redirect( 'http://www.example', 200 );
exit;
}
Unfortunately this runs before the plugins needed to set up the rest api have run.
Where should I place this code to get it right?
Warning!
See answers(s) below.Found a solution myself:
add_action( 'wp_loaded', function () {
// check if there is a 'wp-json' URI part
if (! strpos($_SERVER['REQUEST_URI'], 'wp-json')) {
// No rest api request. Now check if we are on frontend
if ( ! is_admin() ) {
// We are on frontend: redirect now
wp_redirect( 'http://www.example', 200 );
exit();
}
}
});
The above code works fine (tested) if put in a plugin file.
The above code does not work (tested) when put in the root of theme functions.php
file.
- The code in your functions.php should not be running first. Plugins always run before themes (unless you or a plugin has hacked WP core).... Is the plugin doing something that takes a few seconds? What exactly does it need to do when it 'runs'? Is it waiting for a response from another domain? – Dan. Commented Nov 29, 2016 at 7:43
- Which hook are you currently using? – Dan. Commented Nov 29, 2016 at 7:58
- Maybe this question and it's answers can help? – birgire Commented Nov 29, 2016 at 9:13
- @birgure: Doesn't help but thanks. – violacase Commented Nov 29, 2016 at 10:07
1 Answer
Reset to default 1The correct solution is to add the redirect to index.php
in your theme - this will ensure only frontend, non-api based requests are handled.
Sniffing wp-json
in the request is dodgy at best, and will all out break if another plugin overrides the endpoint (which you can do, it's pluggable).
<?php
wp_redirect( 'http://example/', 301 );
exit;
...in wp-content/themes/your-theme/index.php
. And make sure your theme has no other template files, other than a blank functions.php
, and the theme's style.css