How to Filter categories in the permalink structure

Using /%category%/ %postname%/ for the permalink I get a URL string of all the categories that the specific post is included in. I would like the categories in the url to be filtered down.here it is,

I have a celebrity gossip blog and I have this category structure:

www.myblog.com/category_1 › sub category_1 ›sub category_2  Post_name
ex: www.myblog.com/pics/a to c/Aniana Lema /myPostName

I would like to skip the "subcategory_1,2" in the URL,(only display the parent category) ex: www.myblog.com/pics/myPostName

Is it possible?

Topic plugin-list-category-post permalinks filters categories Wordpress

Category Web


strangely familiar to this, but it is different, so here's a modified version

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
        // what happens now actually is the opposite,
        // we end up using the latest category that has a parent
        usort( $cats, '_usort_terms_by_ID' ); // order by ID

        foreach( $cats as $cat ) {

          if ( $cat->parent ) {
              // If there are parent categories, collect them and pick the top most
              $parentcats = explode(" ",get_category_parents( $cat, false, ' ', true ));
              $topcat = $parentcats[0];

          } else {
              $topcat = $cat->slug;
          }
        }
    }
    $permalink = home_url()."/".$topcat."/".$post->post_name;
    return $permalink;
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.