一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

wordpress内容页面title标题调用文章分类

时间:2014-03-08 编辑:简简单单 来源:一聚教程网

现象:wordpress 文章页title标题调用所属分类,使用single_cat_title()方法无任何内容输出。

解析:single_cat_title():该方法只有在分类列表跟标签页面才能正常输出所属分类;

wp_title()也能在分类列表页面title中显示所属分类,固只有文章页title输出所属分类才需额外处理!

get_the_category()方法不带参数,默认为获取文章页所属分类的所有信息,用foreach查看这个方法返回了哪些有用信息可用:

 代码如下 复制代码


$categories=get_the_category();
foreach ($categories as $key => $value) {
echo "$key => $value";
}
?>


页面报“Catchable fatal error: Object of class stdClass could not be converted to string ” 运行错误!
从错误说明中可知$categories返回值中包含有class stdClass类型,我们用var_dump()函数进行输出调试(此函数显示关于一个或多个表达式的结构信息,包括表达式的类型与值。数组将递归展开值,通过缩进显示其结构。) 语句为
var_dump($categories);
显示结果为:

 代码如下 复制代码
array (size=1)
0 =>
object(stdClass)[106]
public 'term_id' => &int 1
public 'name' => &string '未分类' (length=9)
public 'slug' => &string 'uncategorized' (length=13)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 1
public 'taxonomy' => string 'category' (length=8)
public 'description' => &string '' (length=0)
public 'parent' => &int 0
public 'count' => &int 2
public 'object_id' => int 10
public 'filter' => string 'raw' (length=3)
public 'cat_ID' => &int 1
public 'category_count' => &int 2
public 'category_description' => &string '' (length=0)
public 'cat_name' => &string '未分类' (length=9)
public 'category_nicename' => &string 'uncategorized' (length=13)
public 'category_parent' => &int 0


看了这个数组结构可知,要用foreach输出所有有用的分类信息,上面php代码应改为:

 代码如下 复制代码

$categories=get_the_category();
foreach ($categories[0] as $key => $value) {
echo "$key => $value";
} www.111com.net
?>

加上加粗代码部分就能解决“Catchable fatal error: Object of class stdClass could not be converted to string ”这个报错!

到这里,文章页title标题调用所属分类的写法就很明显了,写法如下:

 代码如下 复制代码

if(is_single()){
$categories=get_the_category();
echo $categories[0]->cat_name;
}
?>

热门栏目