Site icon Ryadel

WordPress - How to redirect all posts in one or more Categories, having one or more Tags or other custom conditions

Permalink e URL semantiche su Wordpress con IIS

Being able to redirect a post to another URL is a common need of any WordPress-based Web Master: there are a number of good reasons for doing that, such as: splitting your blog, moving a post from a website to another or to a sub-domain, and so on. Luckily enough, there are a lot of good plugins that can help you to do that, such as:

... and so on.

Unfortunately, most of them are either working with an SourceURL > RedirectURL static list or by adding a widget in the Edit Post page where you can insert the target redirect URL and some additional parameters, such as the redirect type (301 or 302).

What if we need to redirect all posts matching a certain condition? Here are some examples:

  • Redirect all posts in one or more categories.
  • Redirect all posts having one or more tags.
  • Redirect all post within a list on given IDs.

... And so on.

Luckily enough we can do all even without a plugin, thanks to the template_redirect native action hook. This action hook executes just before WordPress determines which template page to load, hence it's the ideal choice if we need to issue redirects based upon any post-based property: all we need to do is to use the add_action()  WP native method to hook it with a custom method that will perform the actual redirect.

Here's a snippet that will 301-redirect all the post in the Test1, Test2 and/or Test3 category:

Place the snippet in the function.php file of your current Worpdress Theme, replacing the sample category names with your actual ones, and test it out. As we can see, we used the WP-native has_category() helper function, which will return TRUE if the post is contained in one or more of the categories identified by the given names, slugs and/or IDs.

IMPORTANT: be sure to properly configure the $new_url  string variable to match your current Permalinks configuration: you might have to add a .html suffix instead of the trailing slash we used in the above sample.

If we want to use Tags instead, we can use the same identical code with the has_tag() helper function, which will return TRUE if the post has one or more tags identified by their namesslugs. and/or IDs:

Needless to say, we can alter the conditional statement in the above code to configure more complex rules, such as:

As we can easily see, the above code is versatile enough to configure the post filter in any possible way: we can mix categories and tags, check up the post ID against a list of given IDs and more.

That's it for now... happy coding!

 

Exit mobile version