Yogesh Chauhan's Blog

How to get category name using post id in WordPress?

in WordPress on February 7, 2021

We can use inbuilt WordPress function get_the_category() to do that.

get_the_category() used to retrieve post category or categories.


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().


$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');


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

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to define visibility for a property in PHP?PHPIs PHP still good for back-end programming?PHPKilling A Project Part 1: What criteria should be used to cancel/kill a project?MiscellaneousHow to define variables in SCSS (Sass)?SCSSWordPress: How to access first and random row values from a repeater field in ACF?WordPressOptional arguments, Default parameters and REST parameters in JavaScriptJavaScriptHow to scroll contents of a an element vertically using JavaScript?JavaScriptWordPress: How to find all posts from a custom post type with specific custom field?WordPressWhat is Git?MiscellaneousHow to redirect or load a new document using JavaScript?JavaScriptHow to add Date and Time picker in HTML and get the values using JavaScript?HTMLHow to create a simple text and image slider using CSS and JavaScript?CSS