Skip to content

Instantly share code, notes, and snippets.

@hslaszlo
Last active August 29, 2023 10:18
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save hslaszlo/3bb7ef52ee424d60f083 to your computer and use it in GitHub Desktop.
Save hslaszlo/3bb7ef52ee424d60f083 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;
?>
@Richzendy
Copy link

// outside the loop
must change $category by $categories

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment