Skip to content

Instantly share code, notes, and snippets.

@slopesweb
Forked from hslaszlo/get-first-category.php
Created September 12, 2022 12:14
Show Gist options
  • Save slopesweb/b4a70a01d58eb105ca1f6807e0e7abb7 to your computer and use it in GitHub Desktop.
Save slopesweb/b4a70a01d58eb105ca1f6807e0e7abb7 to your computer and use it in GitHub Desktop.
Get first category name or id from wordpress post
<?php
// in the loop
$category = get_the_category();
$currentcat = $category[0]->cat_ID;
$currentcatname = $category[0]->cat_name;
$currentcatslug = $category[0]->slug;
// outside the loop
global $post;
$categories = get_the_category($post->ID);
$currentcat = $category[0]->cat_ID;
$currentcatname = $category[0]->cat_name;
$currentcatslug = $category[0]->slug;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment