0

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.com', 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.com', 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. Nov 29 '16 at 7:43
  • Which hook are you currently using? – Dan. Nov 29 '16 at 7:58
  • Maybe this question and it's answers can help? – birgire Nov 29 '16 at 9:13
  • @birgure: Doesn't help but thanks. – violacase Nov 29 '16 at 10:07
0

The 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.com/', 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

  • This indeed works as a charm. Could you spend a few words on how this flow works? – violacase Dec 1 '16 at 14:19
  • It's pretty simple - WordPress will load index.php as the default template for all "normal" frontend requests. However, instead of serving up a theme, we dish out a redirect. – TheDeadMedic Dec 1 '16 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.