We can use inbuilt WordPress function get_the_category() to do that.
get_the_category() used to retrieve post category or categories.
Syntax
get_the_category( int $post_id = false )
where $post_id is optional. The defaults value is false but it defaults to current post ID.
It returns an array of objects, one for each category assigned to the post.
👉 This function only returns results from the default “category” taxonomy and not from custom taxonomies. To get results of custom taxonomies we can use get_the_terms().
Example
$categories = get_the_category('1');//$post->ID
foreach($categories as $category){
echo $category->name;
}
More get_the_category() Examples
Show the First Category Name Only
$categories = get_the_category();
if ( ! empty( $categories ) ) {
echo esc_html( $categories[0]->name );
}
Dump all the categories related to a post
$categories = get_the_category('1');
var_dump($categories);
Get the Post Categories From Outside the Loop
$post = get_post();
if ( $post ) {
$categories = get_the_category( $post->ID );
var_dump( $categories );
}
Read more on: WordPress
category functions pages posts