How do I obtain a list of categories assigned to the current post?

The two functions below are designed to return a list of posts that share the same category as the current post being viewed in single.php

However, when I var_dump on $cat (should be a list of the categories assigned to the current post), I’m not getting what I’m expecting. Do I need to deserialize the array before passing it to the get_posts query?

function get_cats()
{
$post_cats= array();
$categories = get_the_category();
foreach($categories as $cat){
array_push($post_cats, $cat->cat_ID);
}
return $post_cats;
}

//get related posts by category
function ce4_get_related_by_category()
{
global $post;
$cat = implode(',',get_cats());
$catHidden=get_cat_ID('hidden');
$myqueryCurrent = new WP_Query();
$myqueryCurrent->query(array('cat' => "$cat,-$catHidden",'post__not_in' => get_option('sticky_posts')));
$totalpostcount = $myqueryCurrent->found_posts;
if($totalpostcount > 0)
    {
        echo "<ul>";
        $myposts = get_posts(array('cat' => "$cat,-$catHidden",'numberposts' => $cb2_current_count));
        foreach($myposts as $idx=>$post) 
        {
        ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><?php the_excerpt(); ?></li>
        <?php 
        }
        echo "</ul>";
    }
} 

Related posts

Leave a Reply

2 comments

  1. You can use get_the_category()

    It will return an array of category IDs belonging to the current post.

    
    $post_cats= array();
    $categories = get_the_category();
    foreach($categories as $cat) :
    array_push($post_cats, $cat->cat_id);
    endforeach;
    

    Then the $post_cats array will have a list of all the ids.

  2. You can fetch array of IDs alone like this with wp_get_object_terms():

    wp_get_object_terms($id, 'category', array('fields' => 'ids'))
    

    Note that get_the_category() caches results and getting IDs from its return might actually be more efficient than fetching IDs separately with this.