3

We have a WordPress site, which contains posts and pages with different categories. Now we moved a particular category posts into sub domain & we want 301 redirection so that every post from that specific category points to the sub domain. All the posts have .html extension in main domain so we have also changed the sub domain permalink structure to .html. for example: we have http://www.mydomain.com/category/category-name & we have created the sub domain for this category http://category-name.mydomain.com
we can easily redirect this category to sub domain by using .htaccess 301 redirection but the only the home page of the category is redirected not all the posts, we want to redirect all the posts of this category to points to sub domain posts. Sample Post: www.mydomain.com/sample-posts.html of this category need to redirect with category-name.mydomain.com/sample-posts.html.

How to redirect all posts of this category also with this category into sub domain? Also, should we delete all the posts from main domain or we have to keep it ?

5

You can use template_redirect action hook to achieve that:

add_action('template_redirect', 'redirect_category_posts');
function redirect_category_posts() {
    global $post;
    if (is_single($post->ID) && in_category('category-name', $post)) {
        $new_url = "http://category-name.mydomain.com/{$post->post_name}.html";
        wp_redirect($new_url, 301);
        exit;
    }
}

Please note that both posts in main domain and in sub-domain must have the same slug or post_name for this code to work.

  • Where would this code be placed? – Joe Jan 5 '16 at 16:09

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.