1

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?

1
  • if just skipping "subcategory_1", wouldnt' it be "www.myblog.com/pics/Aniana Lema /myPostName/" ?
    – pcarvalho
    Commented Aug 4, 2012 at 9:53

1 Answer 1

2

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;
}

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.