限制显示的分类术语的数量

Mos*_*adi 3 php wordpress categories custom-taxonomy woocommerce

我有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, '    ');
}
Run Code Online (Sandbox Code Playgroud)

结果是:

动作,戏剧,冒险,传记,动画

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

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

题:

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

谢谢

Loi*_*tec 5

相反,使用get_the_term_list()函数,你应该使用get_the_terms()它直接给你一个术语对象数组 (如果你看看函数的源代码,就像get_the_term_list()使用get_the_terms()自己一样).

然后你可以构建一个自定义函数来获得你想要的东西(我不会使用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;
}
Run Code Online (Sandbox Code Playgroud)

此代码位于活动子主题(或主题)的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;
Run Code Online (Sandbox Code Playgroud)

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


- 更新 - (与作者评论相关)

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

// 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;
Run Code Online (Sandbox Code Playgroud)

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

此代码经过测试和运行.