How to change the category in URL for posts in multiple categories?

How can I change the category slug that appears in the URL of a post that’s in multiple categories? I’d like to change the default WordPress behaviour of using the category with the lowest id.

I thought this would do it:

add_filter('post_link', 'mspc_post_link', 1, 2);
function mspc_post_link($link, $post) {
    if (strpos($link, 'bad-category-slug')) {
        $cats = get_the_category($post->ID);
        foreach ($cats as $cat) {
            if ("Bad Category Name" != $cat->cat_name) {
                $slug = $cat->category_nicename;
                break;
            }
        }
        $link = str_replace('bad-category-slug', $slug, $link);
    }
    return $link;
}

But while this kind of does work as expected, it doesn’t change the URL visible to user.

2 Answers
2

Similar plugin but compatible to latest wp version 3.5.2

WP Category Permalink

This plugin allows you to select a ‘main’ category for your posts, for better permalinks and SEO. It uses the same meta data as the “Hikari Category Permalink” and the “sCategory Permalink”, but it has been rewritten using better and cleaner code.

Requires: WP 3.5 or higher
Compatible up to: 3.5.2
Last Updated: 2013-4-18

Leave a Comment