How to display only the parent category in the permalink

You can try out this code here using post_link filter hook.

This filter is applied to the permalink URL for a post prior to returning the processed url by the function get_permalink. Now we are modifying that to suit our requirement i.e, to display only parent category for the child categories and then followed by the post name.

if ( ! is_admin() ){
 add_filter( 'post_link', 'custom_permalink', 10, 3 );
}
function custom_permalink( $permalink, $post, $leavename ) {
  // Get the categories for the post
  $category = get_the_category($post->ID);
  $parent_category = get_category($category[0]->parent);
  if (  !empty($category) && $category[0]->parent == "271" ) {
    $permalink = trailingslashit( site_url("https://wordpress.stackexchange.com/".$parent_category->slug."https://wordpress.stackexchange.com/".$post->post_name."https://wordpress.stackexchange.com/" ) );
  }
  return $permalink;
}

Leave a Comment