I need to redirect about 200 post into category "ricette","svezzamento" and "alimentazione" to url without category. I have this code but not work.

add_action('template_redirect', 'post_redirect_by_custom_filters');

function post_redirect_by_custom_filters() {

global $post;
$catArray = ['ricette','svezzamento','alimentazione'];
if (is_single($post->ID) && has_category($catArray, $post){ 

    $new_url = "https://www.example.com/{$post->post_name}/";
    wp_redirect($new_url, 301);
  • are those url 'working'? why not use htaccess?
    – gael
    May 19, 2020 at 9:32
  • I do not know how to do it
    – SEO Expert
    May 19, 2020 at 9:35

2 Answers 2


Assuming your URLs are of the form /<category>/<post-name>/ (trailing slash optional) then an .htaccess only solution would look something like the following, at the top of your .htaccess file:

# Remove some categories from the URL
RewriteRule ^(ricette|svezzamento|alimentazione)/([^/]+)/?$ /$2/ [R=301,L]

The $2 backreference (in the RewriteRule substitution) matches the <post-name> from the requested URL.

It is preferable to first test with 302 (temporary) redirects in order to avoid potential caching issues.

https://www.example.com/la-crescita/ricette/name-post and I need go to https://www.example.com/name-post

yes "la-crescita" is the first category and "ricette" is the subcategory of "la-crescita". File .htaccess is in the root of WordPress

If /la-crescita is always the main category and "ricette", "svezzamento" and "alimentazione" and subcategories of this main category then you need to modify the above directive to include the category. For example:

RewriteRule ^la-crescita/(ricette|svezzamento|alimentazione)/([^/]+)/?$ /$2/ [R=301,L]
  • Your .htaccess not work
    – SEO Expert
    May 19, 2020 at 11:51
  • Please give an example of the URL you are trying to redirect from/to. (And make sure your browser cache is cleared, as any erroneous 301 redirects will have been cached by the browser.)
    – MrWhite
    May 19, 2020 at 12:01
  • domain.it/la-crescita/ricette/name-post and I need go to domain.it/name-post
    – SEO Expert
    May 19, 2020 at 12:51
  • What is the /la-crescita part of the URL? Where is the .htaccess file located?
    – MrWhite
    May 19, 2020 at 12:59
  • 1
    now work perfectly, thanx!
    – SEO Expert
    May 19, 2020 at 14:53

You need to update site permalink structure from "/%category%/%postname%/" to "/%postname%/".

To update the permalinks Goto: Settings > Permalink

  • Although it seems the OP only wants to redirect a select few categories, not everything?
    – MrWhite
    May 19, 2020 at 15:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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