您的位置 首页 技术

WordPress中函数get_term_link的参数怎么设置

WordPress中函数get_term_link的参数怎么设置? WordPress中函数get_term_link的参数设置问题 推荐:《wordpress教程》 最近帮一个朋…

WordPress中函数get_term_link的参数怎么设置?

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

推荐:《wordpress教程

最近帮一个朋友写企业类主题,需要对产品设定一个专门的 post type 名叫 product,为了管理方便性,我对 product 设置了专门的分类类型和标签类型,分类类型为 product_cat(WordPress 本身的分类类型为 category)。

为何要用 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的参数怎么设置的详细内容,更多请关注24课堂在线网其它相关文章!

本文来自网络,不代表24小时课堂在线立场,转载请注明出处:https://www.24ketang.cn/27234.html

为您推荐

返回顶部