Wordpress:使用functions.php和foreach循环

时间:2012-09-08 21:52:54

标签: 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_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_cat_slug($post->ID)始终返回null。为什么?我错过了什么? 任何建议非常感谢。

2 个答案:

答案 0 :(得分:2)

在get_category之前肯定不应该有&符号,实际上需要a Category ID and not a post ID。)

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

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

按照wordpress函数样式,如果你用get_...命名你的函数,它应该return $category->slug而不是echo,这意味着你必须{{1}在模板循环中。

你的循环依赖于WP_Query,它属于模板文件,而不是functions.php。哪个模板文件取决于您的循环服务的目的以及您希望显示它的位置。 index.php是主要post循环的逻辑选择,尽管archive.php,single.php或任何预先存在的主题特定模板可能都有意义,就像您创建的任何自定义非标准模板一样。

答案 1 :(得分:1)

可能是你的演员阵容

$post_id = intval($ID);

ref

您是否尝试过记录每一步?所以你可以准确地看出它出错的地方