WordPress: Remove Parent Category from Permalink

WordPress allows you to include the categories within the permalink structure using /%category%/%postname%. This can be very handy, but if your post is nested within a few categories the URL can start to get too long and messy.

If you want to remove the parent category from the permalink structure in WordPress, simply paste the following code into your functions.php file:

add_filter( 'post_link', 'remove_parent_cats_from_link', 10, 3 );
function remove_parent_cats_from_link( $permalink, $post, $leavename )
{
$cats = get_the_category( $post->ID );
if ( $cats ) {
// Make sure we use the same start cat as the permalink generator
usort( $cats, '_usort_terms_by_ID' ); // order by ID
$category = $cats[0]->slug;
if ( $parent = $cats[0]->parent ) {
// If there are parent categories, collect them and replace them in the link
$parentcats = get_category_parents( $parent, false, '/', true );
// str_replace() is not the best solution if you can have duplicates:
// myexamplesite.com/luxemburg/luxemburg/ will be stripped down to myexamplesite.com/
// But if you don't expect that, it should work
$permalink = str_replace( $parentcats, '', $permalink );
}
}
return $permalink;
}
Free Graphics, Icons, Tutorials
Free Graphics Free Christmas Vector Icon Graphics Pack 2017Free Fitness Vector Icons Graphics PackFree Camping Vector Graphics PackFree Summer Graphics PackFree File Icon PackFree Fast Food Vector Graphics
Sharing is caring...
Like & Follow
Share the love, share this page! Facebook Twitter Digg Reddit LinkedIn Pinterest Email
Close [X]
The Web Taylor
1000 Lakeside North Harbour Portsmouth, Hampshire PO6 3EN
02392 123358