Wordpress:使用functions.php和foreach循环

Wordpress:使用functions.php和foreach循环,php,wordpress,Php,Wordpress,为什么如果我从functions.php中调用自定义函数,它就不能工作 我的自定义功能: function get_cat_slug($ID) { $post_id = (int) $ID; $category = &get_category($post_id); echo $category->slug; } 在所有的柱子上打圈,就像这样: $args = array( 'numberposts' => -1 ); $posts = get_

为什么如果我从functions.php中调用自定义函数,它就不能工作

我的自定义功能:

function get_cat_slug($ID) {
    $post_id = (int) $ID;
    $category = &get_category($post_id);
    echo $category->slug;
}
在所有的柱子上打圈,就像这样:

$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);

}
但是,
get\u cat\u slug($post->ID)
始终返回
null
。为什么?我错过了什么?
非常感谢您的建议

也许你的演员应该是

$post_id = intval($ID);


你试过记录每一步吗?因此,您可以准确地看到它的错误所在

在get_类别之前,绝对不应该有一个符号,这实际上需要一个符号。)

返回一个类别数组(因为帖子可以有多个类别),您也不需要指定(int)。如果您只想回显第一只猫的鼻涕虫(假设为单一分类),请尝试:

但是,遵循wordpress函数样式,如果您使用
get\u…
命名函数,它应该
返回$category->slug
,而不是
echo
它,这意味着您必须
echo get\u cat\u slug($post->ID)在模板循环中


循环依赖于WP_查询,该查询属于模板文件,而不是functions.php。哪个模板文件取决于循环的用途和显示位置。index.php是主post循环的逻辑选择,尽管archive.php、single.php或任何预先存在的主题特定模板可能有意义,您创建的任何自定义非标准模板也是如此。

更改后,“我的函数”仍然返回空值。如何检查函数是否被调用?在哪里运行循环?您应该检查在get_cat_slug调用中是否实际传递了有效的post id
echo$post->ID
在调用get_cat_slug函数之前。如果看到空输出,则调用该函数。因此,您需要在模板文件(index.php,可能)中运行循环。它在functions.phpYes中不起作用。为什么这在functions.php中不起作用?甚至我在foreach循环中也有这个?
function get_cat_slug($post_id) {
  $cat_id = get_the_category($post_id);
  $category = get_category($cat_id[0]);
  echo $category->slug;
}