Instead using
get_the_term_list()
function, you should useget_the_terms()
which will give you directly an array of terms (asget_the_term_list()
is usingget_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 — 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