在几个主题模板中,我有代码来检索当前帖子或类别页面的类别名称和slug。它在环路之外。以下是重复代码:
global $post;
$categories = get_the_category($post->ID);
if ( $categories ) {
foreach ($categories as $category) {
$dw_category_slug = $category->slug;
$dw_category_name = $category->name;
}
}else {
$dw_category_slug = \'utopia\';
}
我希望能够将其包含在函数文件中,而不是在多个地方编写它。这是我在函数文件中尝试的内容:
add_action(\'wp_head\', \'dw_get_category\');
function dw_get_category() {
global $post;
$categories = get_the_category($post->ID);
if ( $categories ) {
foreach ($categories as $category) {
$dw_category_slug = $category->slug;
$dw_category_name = $category->name;
}
} else {
$dw_category_slug = \'utopia\';
}
$dw_category[] = array(\'name\' => $dw_category_name, \'slug\' => $dw_category_slug);
return $dw_category;
}
我希望能够写出
$dw_category[\'name\']
在模板文件中调用类别名称。我知道这样做是错误的。我是否需要将其分为2个函数,以便该函数只返回一个值?还是有其他方法可以做到这一点?以类的形式编写?
如果感兴趣,url为http://lenoremalenblog.com
谢谢你的时间。
最合适的回答,由SO网友:kaiser 整理而成
你不需要钩住dw_get_category()
作用只需这样做:
function dw_get_category() {
global $post;
$categories = get_the_category($post->ID);
if ( $categories ) {
foreach ($categories as $category) {
$dw_category_slug = $category->slug;
$dw_category_name = $category->name;
}
} else {
$dw_category_slug = \'utopia\';
}
$dw_category = array(\'name\' => $dw_category_name, \'slug\' => $dw_category_slug);
return $dw_category;
}
然后这样称呼它:
$the_post_cats = dw_get_category();
echo \'Category: \'.$the_post_cats[\'name\'];
echo \'Slug: \'.$the_post_cats[\'slug\'];