Question

What’d be an optimal way to redirect the home page of a WordPress site to a category archive without involving external factors (e.g. Apache’s .htaccess) i.e. within WordPress?

Why?

(Only to justify the question. Please let this not turn the question into too localized.)

It’s a news site. The categories are used as Editions, for example:

  • US: http://example.com/main/
  • UK: http://example.com/uk/
  • Japan: http://example.com/jp/

(The category based is removed.)

The visitor is to be taken to the US edition (http://example.com/main/) by default no matter where he/she is from, and that is why I want the redirect.

Options Considered

I know I can simply modify the main query and have the home page only include posts from the specific category (Edition). But the way the features of the site are constructed, I find the redirect to be more feasible and moreover appropriate.

Aside from that, I want the URLs to make the current location clear to the visitor.

As for why I can’t use the simpler and better performant .htaccess-based redirection — all the functionality needs to be either within the theme or as a separate plugin. Hence, looking for the best way to do it with WordPress/PHP.

I’ve also considered adding this in home.php template file:

<?php
    wp_redirect( 'http://example.com/main/' );
?>

And decided against it as it “almost doubles server load for home page”.

2 Answers
2

Eliminating all of the other solutions, there is at least one remaining: template_redirect:

function wpse121308_redirect_homepage() {
    // Check for blog posts index
    // NOT site front page, 
    // which would be is_front_page()
    if ( is_home() ) {
        wp_redirect( get_category_link( $id ) );
        exit();
    }
}
add_action( 'template_redirect', 'wpse121308_redirect_homepage' );

You will need to pass the appropriate category $id, of course.

The benefit of redirecting at template_redirect is that you only get one template-load taking place, rather than a second redirect after the template loads.

Edit

As per @Milo’s comment, you could also try hooking into the process even earlier, at pre_get_posts, thereby potentially saving an entire query request:

add_action( 'pre_get_posts', 'wpse121308_redirect_homepage' );

Leave a Reply

Your email address will not be published. Required fields are marked *