Mostafa AHmadi Mostafa AHmadi - 3 months ago 40
PHP Question

Limit the number of taxonomy terms diplayed

I have 2 taxonomy sets

product_cat
and
tvshows_cat
. There are 12 terms for each set.

A product can have, up to 12 terms (but never from the 2 sets at the same time).

I use this code to show the term list in the product page:

$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, ' ');
}


The result is:


Action, Drama, Adventure, Biography, Animation


The problem is that, in some cases, there is not enough space to show all terms.

I need to limit number of terms to 2 terms.

Question:

How can I limit the number of terms applied to two?

Thanks

Answer

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

Then that you can build a custom function to get what you want (I will not use implode() function or any other one php function as we want only 2 terms.)

Note: You don't need strip_tags() function here

So your code will be:

// 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;
}

This code goes in function.php file of your active child theme (or theme) or any plugin files…

Then below is your code:

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

// Displaying 2 categories terms max
echo $cats . $tvcats;

This code goes on your php templates file


— update — (related to author comment)

Or without function, your code will be:

// 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;

This code goes on your php templates files

This code is tested and works.