WordPress中函数get_term_link的参数设置问题

2019-10-30,

为何要用 get_term_link?:
新类型的分类是无法用 <?php echo get_category_link( $category_id ); ?> 输出分类链接地址的,需要用 get_term_link() 函数,此函数用法如下:
<?php get_term_link( $term, $taxonomy ); ?>
具体参考 WordPress Codex:http://codex.wordpress.org/Function_Reference/get_term_link
问题:
举个例:
- 自定义分类ID的变量为 $term,$term 是根据后台设置而改变的,为了方便说明,这里假定后台参数为 $custom_term = 8
- 我要获取自定义分类ID为 $term 的分类链接地址,那么按照官方说明应该是:
<?php
$term = $custom_term;
echo get_term_link( $term, 'product_cat');
?>
看似没错,但问题来了,这样会返回错误:
Catchable fatal error: Object of class WP_Error could not be converted to string in.。没错啊,直接用 echo $term; 输出结果的确是 8,这就让人郁闷了……
不过如果你直接这样:
<?php echo get_term_link( 8, 'product_cat'); ?>
又能正常工作。
解决方法:
在 WordPress Codex 打转时,无意中看到国外朋友也碰到这个问题,然后他自己解决了,顿悟……传送门 》
原来是变量类型问题,这 get_term_link 函数和其它常用的 WordPress 函数不同,不会自己转换变量类型,你得先把字符类转换为整数才能正常工作,好Orz的函数!
下面这样就能正常工作:
(坐在沙发上的Bolo注:intval($term, 10)会更好,不然$term值太大的时候会有进制转换问题,要么就用(int)$term)
<?php
$term = $custom_term;
echo get_term_link( intval($term), 'product_cat');
?>
所以,以后遇到类似这郁闷的函数,就要考虑是不是变量数据类型问题了。
折腾玩(完)。

《WordPress中函数get_term_link的参数设置问题.doc》

下载本文的Word格式文档,以方便收藏与打印。