我们可以使用
// 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\' );
其中,我们将过滤器回调定义为:
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;
}
更新:OP似乎只想得到一个以逗号分隔的术语名称列表。
我们也可以执行以下操作:
$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\' )
我们还可以为此创建一个通用包装器。这里有一个未经测试的建议:
/**
* 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;
)
然后我们可以在循环中使用它,如:
echo get_wpse_terms_attribute_csv(
$post_id = get_the_ID(),
$taxonomy = \'product_cat\',
$attribute = \'name\',
$length = 2
);
希望您可以根据自己的需要进一步调整!