WordPress文档显示,数组是get\\u The\\u terms中可接受的分类参数(https://developer.wordpress.org/reference/functions/get_the_terms/). 如果您试图获取多个分类法,那么数组就可以工作。如果您只想获得一种分类法,它甚至可以工作。但是,按顺序获取两个单独的分类法数组会破坏此代码。
在最初发布的代码中,替换为:
$size_terms = get_the_terms( $post->ID , array( \'sizes\') );
换言之:
$size_terms = get_the_terms( $post->ID , \'sizes\' );
并将其替换为:
$color_terms = get_the_terms( $post->id , array( \'colors\') );
换言之:
$color_terms = get_the_terms( $post->id , \'colors\' );
解决了问题。
另一种可行的方法是一次检索两组分类术语,然后梳理WP\\u Term对象以准确找到所需内容。在大多数情况下,这可能是更好的解决方案。
function display_single_product_taxonomy_terms() {
global $post;
$tax_terms = get_the_terms( $post->ID , array( \'sizes\',\'colors\') );
// create the markup variables
$color_markup = \'\';
$size_markup = \'\';
// init counters
$color_counter = 0;
$size_counter = 0;
foreach ( $tax_terms as $tax_term ) {
if( $tax_term->taxonomy == \'colors\' ) {
// this is a colors term; increment color counter
$color_counter++;
// add to color markup
$color_markup .= ($color_counter > 1)? "; " : "";
$color_markup .= \'<a href="/shades/color/\' . $tax_term->slug . \'">\' . str_replace(", and,"," and",str_replace("-", ", ", $tax_term->slug)) . \'</a>\';
} else {
// this is a sizes term; increment size counter
$size_counter++;
// add to size markup
$size_markup .= ($size_counter > 1)? "; " : "";
$size_markup .= \'<a href="/shades/size/\' . $tax_term->slug . \'">\' . str_replace("-", " ", $tax_term->slug) . \'</a>\';
}
};
echo \'<div class="single-product-taxonomy-terms">\' . PHP_EOL;
if ( $size_counter > 0 ) {
echo \'<p>\'. __("Similar size shades: ","bright-side") . $size_markup . \'</p>\' . PHP_EOL;
};
if ( $color_counter > 0 ) {
echo \'<p>\' . __("Similar color shades: ","bright-side") . $color_markup . \'</p>\' . PHP_EOL;
};
echo \'</div>\' . PHP_EOL;
};
add_action( \'woocommerce_single_product_summary\', \'display_single_product_taxonomy_terms\', 101, 0 );