[resolved] Get post category outside the loop (3 posts)

  1. tipone
    Posted 6 years ago #

    Boys and girls. i can not find the solution of this:
    I am writing a function in functions.php to show all post titles depending on opened post.
    F.e If the post belongs to category Books and there is another posts within this category - show those post titles.

    The trick bhind this is - the function is outside the loop. I am trying to get the active category Id, but it always returns last created category Id
    $categories = get_the_category();
    $category = $categories[0];
    $cat_id = $category->cat_ID;
    echo $cat_id;

    Do you know, how to return the category id outside the loop when reading a post?

  2. MichaelH
    Posted 6 years ago #

    According to Function_Reference/get_the_category

    This tag may be used outside The Loop by passing a post id as the parameter

    $categories = get_the_category($post_id_goes_here);

  3. tipone
    Posted 6 years ago #

    Holy cow! That is why you should not continue to work a on one function if you canot solve something :D
    Thank MichalelH!

Topic Closed

This topic has been closed to new replies.

About this Topic