1

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);
    exit;
}
}
2
  • are those url 'working'? why not use htaccess?
    – gael
    Commented May 19, 2020 at 9:32
  • I do not know how to do it
    – SEO Expert
    Commented May 19, 2020 at 9:35

2 Answers 2

1

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]
9
  • Your .htaccess not work
    – SEO Expert
    Commented 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
    Commented May 19, 2020 at 12:01
  • domain.it/la-crescita/ricette/name-post and I need go to domain.it/name-post
    – SEO Expert
    Commented May 19, 2020 at 12:51
  • What is the /la-crescita part of the URL? Where is the .htaccess file located?
    – MrWhite
    Commented May 19, 2020 at 12:59
  • 1
    now work perfectly, thanx!
    – SEO Expert
    Commented May 19, 2020 at 14:53
0

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

To update the permalinks Goto: Settings > Permalink

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

Your Answer

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

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