How to Set Both Category and Sub-Category Level at Root. It should also obey post rule as /category/sample-post and /sub-catgeory/sample-post?

You’ll need to define your own rewrite tag, and add the tag into the permalink structure.

  • add_rewrite_tag() to register the new structure tag
  • available_permalink_structure_tags filter to add to Permalinks interface
  • post_link filter to change the URL of posts

Below is untested and incomplete code, but should get you pretty far.

add_action( 'init', static function () {
    add_rewite_tag( '%one_category%', '(.+)', 'one_category=' );
} );

add_filter( 'available_permalink_structure_tags', function ( array $tags ) : array {
    $tags['one_category'] = 'Only one category';
    return $tags;
} );

add_filter( 'post_link', static function ( string $permalink, $post ) : string {
    if ( false === stripos( $permalink, '%one_category%' ) ) {
        return $permalink;
    }

    $categories = get_the_category( $post->ID );
    $category = array_pop( $categories );

    return str_replace( '%one_category%', $category->slug, $permalink );
}, 10, 2 );