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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Recursive WITH Queries in Postgres (Common Table Expressions)PostgresWhere is the PHP log file located on Mac OS?PHPSQL GROUP BY StatementSQL/MySQLHow to create a dynamic countdown using HTML and JavaScript?HTMLHow to animate list items using CSS and JavaScript?CSSHigher Order Functions in JavaScript with ExamplesJavaScriptHow to add CurrencyPipe in TypeScript file in Angular 9 Project?AngularConfiguring Modules with @forward rule in SCSS (Sass)SCSSWhat is the correct way to enqueue multiple CSS files in WordPress?WordPressHow to add a Pie Chart in Angular App?AngularAngular: Templates, directives, data binding, Services and dependency injectionAngularHow to link/add CSS file to HTML Document?CSS