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:

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


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


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.

Need Your Help

Why is mclappy slower than apply in this case?

r parallel-processing apply smoothing mclapply

i'm pretty confused. I want to speed up my algorithm by using mclapply:parallel, but when I compare time efficiency, apply still wins.

Gracefully ending a thread that's waiting on a blocking queue

java multithreading blockingqueue

I'm having an issue with a multi-threaded server I'm building as an academic exercise, more specifically with getting a connection to close down gracefully.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.