Get WordPress category level

/**
 * Gets category level/depth in the hierarchy.
 *
 * @see https://wpcodebook.com/wordpress-get-category-level/
 * @see https://developer.wordpress.org/reference/functions/get_ancestors/
 *
 * @param int $category_id The ID of the category to get the level for.
 * @return int
 */
function wpcodebook_get_category_level( $category_id ) {
	return count( get_ancestors( $category_id, 'category', 'taxonomy' ) );
}

Leave a Comment