Sometimes you want to redirect posts in certain categories to a new location / domain name. You do not want to redirect the entire website to a new website, but only part of it. This because you perhaps split up your website into multiple websites. Well you are in luck. With WordPress this is possible with the use of template_redirect.

Template Redirect

Thanks to Ryan’s post we came to realize how easy this redirecting based on category is with WordPress built in template_redirect . This function is normally used to redirect / decide what template to load, but it can also be used to redirect to that same category on another website.

Example Category Redirect

Here is an example of two sets of redirect we used before. One redirecting to this current website and one to our partner WooAid:

// redirect WP stuff to WP Villain and Woo  stuff to Wooaid

add_action('template_redirect', __NAMESPACE__ . '\\post_redirect_by_custom_filters');
function post_redirect_by_custom_filters() {
    global $post;
    // this array can contain category names, slugs or even IDs.
    $catArray = ['Sage Starter Theme', 'Sage', 'WordPress', 'Trellis', 'Bedrock', 'Plugins', 'Themes'];
    if (is_single($post->ID) && has_category($catArray, $post)) {
        $new_url = "https://wpvilla.in/{$post->post_name}/";  
        wp_redirect($new_url, 301);
        exit;
    }
}

add_action('template_redirect', __NAMESPACE__ . '\\woo_post_redirect_by_custom_filters');
function woo_post_redirect_by_custom_filters() {
    global $post;
    // this array can contain category names, slugs or even IDs.
    $catArray = ['WooCommerce'];
    if (is_single($post->ID) && has_category($catArray, $post)) {
        $new_url = "https://wooaid.com/{$post->post_name}/";  
        wp_redirect($new_url, 301);
        exit;
    }
}

These two examples are used in a Sage 8 based theme so namespacing is mandatory. For themes that do not use namespacing you can leave that part out.

Recommended Posts

No comment yet, add your voice below!


Add a Comment

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