Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 ?

share|improve this question

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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