从WP获取类别ID

I am trying to get 2nd level category of a single Post.

A Post is under this hierarchy Sports > Football > premier league

i want to get the ID for Sport how can i do this.

Thank You.

You can get all first level categories by this code for particular post

 $cat = get_the_category($post_id);

then by this one you can get child categories

$child_categories=get_categories(
    array( 'parent' => $cat->cat_ID )
);

Try this, this will work for 'nth' level

$category = get_the_category(); 
$parent = get_ancestors($category[0]->term_id,'category');
if (empty($parent)) {
  $parent[] = array($category[0]->term_id);
}
$parent = array_pop($parent);
$parent = get_category($parent); 
if (!is_wp_error($parent)) {
  var_dump($parent);
} else {
  echo $parent->get_error_message();
}


Reference: