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
get_cat_slug($post->ID);
}
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:
Following wordpress function styles, though, if you’re naming your function with
get_...
, it shouldreturn $category->slug
rather thanecho
it, meaning you’d have toecho 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.
May be your cast should be
ref
Have you tried to log every step? So you can exactly see where it goes wrong