php固定数量分类,php – 限制diplayed的分类术语数量

我有2个分类集product_cat和tvshows_cat.每套有12个术语.

一个产品最多可以有12个术语(但不能同时使用2个).

我使用此代码在产品页面中显示术语列表:

$cats = get_the_term_list($post->ID, 'product_cat', '', ' ', '');

$tvcats = get_the_term_list($post->ID, 'tvshows_cat', '', ' ', '');

if (!empty($cats)){

echo strip_tags($cats, ' ');

}elseif(!empty($tvcats)){

echo strip_tags($tvcats, ' ');

}

结果是:

Action, Drama, Adventure, Biography, Animation

问题是,在某些情况下,没有足够的空间来显示所有术语.

我需要将条款数量限制为2个条款.

题:

如何限制应用于两个的术语数量?

谢谢

解决方法:

Instead using get_the_term_list() function, you should use get_the_terms() which will give you directly an array of terms objects (as get_the_term_list() is using get_the_terms() herself if you look to the source code of the function).

然后你可以构建一个自定义函数来获得你想要的东西(我不会使用implode()函数或任何其他一个php函数,因为我们只需要2个术语.)

注意:这里不需要strip_tags()函数

所以你的代码将是:

// This function goes first

function get_my_terms( $post_id, $taxonomy ){

$cats = get_the_terms( $post_id, $taxonomy );

foreach($cats as $cat) $cats_arr[] = $cat->name;

if ( count($cats_arr) > 1) $cats_str = $cats_arr[0] . ', ' . $cats_arr[1]; // return first 2 terms

elseif ( count($cats_arr) == 1) $cats_str = $cats_arr[0]; // return one term

else $cats_str = '';

return $cats_str;

}

此代码位于活动子主题(或主题)的function.php文件或任何插件文件中…

然后下面是你的代码:

$cats = get_my_terms( $post->ID, 'product_cat' );

$tvcats = get_my_terms( $post->ID, 'tvshows_cat' );

// Displaying 2 categories terms max

echo $cats . $tvcats;

这段代码放在你的php模板文件中

— update — (related to author comment)

或者没有功能,您的代码将是:

// Product categories

$cats = get_the_terms( $post->ID, 'product_cat' );

foreach($cats as $cat) $cats_arr[] = $cat->name;

if ( count($cats_arr) > 1) $cats_str = $cats_arr[0] . ', ' . $cats_arr[1]; // return first 2 terms

elseif ( count($cats_arr) == 1) $cats_str = $cats_arr[0]; // return one term

else $cats_str = '';

// TV shows categories

$tvcats = get_the_terms( $post->ID, 'tvshows_cat' );

foreach($tvcats as $tvcat) $tvcat_arr[] = $tvcat->name;

if ( count($tvcat_arr) > 1) $tvcats_str = $tvcat_arr[0] . ', ' . $tvcat_arr[1]; // return first 2 terms

elseif ( count($tvcat_arr) == 1) $tvcats_str = $tvcat_arr[0]; // return one term

else $tvcats_str = '';

// The Display of 2 categories

echo $cats_str . $tvcats_str;

这段代码放在你的php模板文件中

此代码经过测试和运行.

标签:wordpress,php,woocommerce,categories,custom-taxonomy

来源: https://codeday.me/bug/20190715/1465480.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值