• Resolved eadwig

    (@eadwig)


    Hello

    I understood every bit of the description given for get_the_category() in Codex, but cannot make the function retrieve anything but an empty value using code in the following format:

    $categories = get_the_category(5);

    if ( ! empty( $categories ) ) {
    echo esc_html( $categories[0]->name );

    I made absolutely sure the correct category ID is 5 in the admin screen. What could possibly prevent get_the_category() from retrieving the category name? I spent a day googling solutions but could not find a solution that works for the life of me.

    The page I need help with: [log in to see the link]

Viewing 6 replies - 1 through 6 (of 6 total)
  • The argument is the post ID, not the category ID.

    Moderator bcworkz

    (@bcworkz)

    get_the_category() returns category terms assigned to the current or specified post. If you want the actual category term object with ID=5, do $term = get_category( 5 );

    Hi!
    You Guys have Missed Something! Try this code!
    $categories = get_the_category();

    if ( ! empty( $categories ) ) {
    echo esc_html( $categories[4]->name ); //Show the 5th Category Name Only
    }
    //(Echoes the first array element ([0]) of $categories.)
    //For 5th array element ([4]) of $categories.

    • This reply was modified 5 years, 9 months ago by coder01.
    • This reply was modified 5 years, 9 months ago by coder01.
    Thread Starter eadwig

    (@eadwig)

    Thanks everyone for the replies. Passing a post ID into get_the_category() returned ‘Array’ and into get_category returned an empty value. Eventually, I used the code below to achieve the desired outcome:

    $catObj = get_category_by_slug('notices');
    $catName = $catObj->name;
    echo '<h2>'.$catName.'</h2>';
    Thread Starter eadwig

    (@eadwig)

    Btw, I am confused about the differences between ‘category name’, ‘category term’ and ‘category slug’. Is the category term the same as the category slug?

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘get_the_category() returns an empty value’ is closed to new replies.