Remove sub category slug from permalink URL of blog post and custom post type in WordPress

I have standard posts and custom posts utilised on my site. Basically for standard and custom posts we want the following.

parent post category e.g.: “blog”
then sub categories to this parent category. So e.g.:

Read More

Blog (parent Category)

News (Sub Category)

LatestNewsPostOne

events (sub category)

LatestEvnntssPostOne

So posts can live in any or all of these categories. If you visit the “blog” category you will have the following permastructure:

domain.com/blog

If you visit “news” category you will have the following permastructure:

domain.com/blog/news

However when you visit “LatestNewsPostOne” you would have the following permastructure:

domain.com/blog/LatestNewsPostOne

So in the last example you will notice that once you click on an individual post to open it. the subcategory disappears from the url. Currently my site leaves in the subcategory which I don’t want.

Does anyone know of any solution to implement this on a WordPress site?

Related posts

Leave a Reply

1 comment

  1. I’ve figured it out. Below is my code to get rid of the subcategory slug from blog post permalink URL, I added the following to my functions.php file in the theme folder:

    add_filter(
    'post_link',
    'custom_post_type_link',
    10,
    3); function custom_post_type_link($permalink, $post, $leavename) {
    if (!gettype($post) == 'post') {
        return $permalink;
    }
    switch ($post->post_type) {
        case 'post':
            //$permalink = get_home_url() . '/' . $post->post_name . '/';
    
            $cats = get_the_category($post->ID);
            $subcats = array();
            foreach( $cats as $cat ) {
                $cat = get_category($cat->term_id);
                if($cat->parent) { $subcats[] = sanitize_title($cat->name); }
            }
            if($subcats) {
                foreach($subcats as $subcat) {
                    $subcat = $subcat.'/';
                    $permalink = str_replace($subcat, "", $permalink);
                }
            }
    
    
            break;
    }
    
    return $permalink;}