How to display only the parent category in the permalink

How it is possible to display only the parent category of the post. It contains two sub categories and I want to eliminate it.

Example:
myblog.com/parent_category/post_name

Read More

This is only what I want.

Related posts

Leave a Reply

1 comment

  1. 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('/'.$parent_category->slug.'/'.$post->post_name.'/' ) );
      }
      return $permalink;
    }