YogeshChauhan . com

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.

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

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How states work in React?Reactfirst-of-type and last-of-type selectors in CSSCSSLearn to Implement Estimated Reading Time using PHP Part 2: Final Implementation with Source CodePHPSQL Right JoinSQL/MySQLHow to make WordPress main stylesheet (style.css)?WordPressThe Lending Club Analysis using Logistic Regression and Random Forest in RStudioMiscIntroduction to components and templates Part 4: Pipes and DirectivesAngularHow to create rotating texts using JavaScript and CSS?CSSOrder By and Group By in PostgresPostgresHow to avoid element shift on border change while hovering in CSS?CSSHow to create a flip pricing table using CSS and JavaScript?CSSWhat are Conditional Tags in WordPress?WordPress