We can limit the number of displayed terms with
// Add filter
add_filter( 'get_the_terms', 'wpse_limit_terms' );
// Get terms
$cats = get_the_term_list($post->ID, 'product_cat', '', ' ', '');
$tvcats = get_the_term_list($post->ID, 'tvshows_cat', '', ' ', '');
// Remove filter
remove_filter( 'get_the_terms', 'wpse_limit_terms' );
where we define the filter callback as:
function wpse_limit_terms( $terms )
{
// Adjust to your needs
$length = 2;
// Slice the terms array
if( is_array( $terms ) && count( $terms ) > $length )
$terms = array_slice( $terms, $offset = 0, $length );
return $terms;
}
Update:
It looks like OP only wants to get a comma separated list of term names.
We can alternatively do the following:
$taxonomy = 'product_cat'; // Adjust to your needs
$terms = get_the_terms( get_the_ID(), $taxonomy );
if( is_array( $terms ) && ! empty( $terms ) )
echo join( ',', wp_list_pluck( array_slice( $terms, 0, 2 ), 'name' )
We could also create a general wrapper for this. Here's an untested suggestion:
/**
* Custom wrapper
*
* @return string Comma seperated term attribute values
*/
function get_wpse_terms_attribute_csv( $post_id, $taxonomy, $attribute, $length = 0 )
{
$csv = '';
// Nothing to do for non-attributes
if( ! in_array( $attribute, [ 'name', 'term_id', 'slug' ] ) )
return $csv;
// Nothing to do if taxonomy doesn't exists
if( ! taxonomy_exists( $taxonomy ) )
return $csv;
// Fetch terms
$terms = get_the_terms( $post_id, $taxonomy );
// Nothing to do if we don't have a non-empty array of terms
if( ! is_array( $terms ) || empty( $terms ) )
return $csv;
// Slice the array if needed
if( (int) $length > 0 )
$terms = array_slice( $terms, 0, (int) $length )
// Pluck the terms array
$terms = wp_list_pluck( $terms, $attribute );
// Generate a list of comma separated term attribute values
$csv = join( ',', $terms );
return $csv;
)
We can then use this within the loop like:
echo get_wpse_terms_attribute_csv(
$post_id = get_the_ID(),
$taxonomy = 'product_cat',
$attribute = 'name',
$length = 2
);
Hopefully you can adjust this further to your needs!