WordPress: Working with functions.php and foreach loop

Why if I call a custom function from within functions.php it does not work?

My custom function:

Read More
function get_cat_slug($ID) {
    $post_id = (int) $ID;
    $category = &get_category($post_id);
    echo $category->slug;
}

Loop trough all posts, like that:

$args = array(
 'numberposts' => -1
);  
$posts = get_posts($args);
foreach ($posts as $post){
   // and withing this lopp I would like to get a category slug
   // so I am calling my custom function, also included in functions.php
   get_cat_slug($post->ID);

}

But, get_cat_slug($post->ID) always return null. Why? What am I missing?
Any suggestions much appreciated.

Related posts

Leave a Reply

2 comments

  1. There should definitely not be an ampersand before get_category, which actually needs a Category ID and not a post ID.)

    get_the_category returns an array of categories (because posts can have multiple), and you also do not need to specify (int). If you only want to echo the slug of the first cat (assuming single categorization,) try:

    function get_cat_slug($post_id) {
      $cat_id = get_the_category($post_id);
      $category = get_category($cat_id[0]);
      echo $category->slug;
    }
    

    Following wordpress function styles, though, if you’re naming your function with get_..., it should return $category->slug rather than echo it, meaning you’d have to echo get_cat_slug($post->ID); in your template loop.

    Your loop depends on a WP_Query, which belongs in a template file and not functions.php. Which template file depends on what purpose your loop is serving and where you would like to display it. index.php is the logical choice for a primary post loop, though archive.php, single.php, or any pre-existing theme-specific template might make sense, as would any custom, non-standard template you create.