Php 显示自定义产品属性和单个产品上的所有术语
我在WooCommerce单一产品页面上创建了六个自定义属性,其中包含一个自定义函数。它们包括:图标、标签和术语 基于应答代码,我使用了以下函数(与自定义HTML标记不同,与WooCommerce product-attributes.php模板中的标记不同):Php 显示自定义产品属性和单个产品上的所有术语,php,wordpress,woocommerce,custom-taxonomy,taxonomy-terms,Php,Wordpress,Woocommerce,Custom Taxonomy,Taxonomy Terms,我在WooCommerce单一产品页面上创建了六个自定义属性,其中包含一个自定义函数。它们包括:图标、标签和术语 基于应答代码,我使用了以下函数(与自定义HTML标记不同,与WooCommerce product-attributes.php模板中的标记不同): add_action('woocommerce_single_product_summary','pa_custom_attributes',25); 函数pa_自定义属性(){ 全球$产品; $attributes=$product-
add_action('woocommerce_single_product_summary','pa_custom_attributes',25);
函数pa_自定义属性(){
全球$产品;
$attributes=$product->get_attributes();
如果(!$attributes)返回;
$out='';
foreach($attributes作为$attribute){
如果($attribute->get_variation())继续;
如果($attribute->is_taxonomy()){
$taxonomy=$attribute->get_name();
$taxo_obj=$attribute->get_taxonomy_object();
$name=$taxo\u obj->attribute\u name;
$label=$taxo_obj->attribute_label;
$label\u name=wc\u attribute\u label($taxonomy);
$out.='';
$out.='';
$out.=''.$label_name'.';
$out.='';
$terms=wp\u get\u post\u terms($product->get\u id(),$taxonomy,array('fields'=>'names');
foreach($terms作为$term\u名称)
$term\u name['names']=$term\u name;
$out.=内爆(“,”,$term_name);
$out.='';
}否则{
$value_string=内爆(“,”,$attribute->get_options());
$out.='';
$out.=''.$taxonomy'.:';
$out.=''.esc_html($value_string)。'';
}
}
$out.='';
回音$out;
}
该函数工作正常,但存在一个问题:如果特定属性的项不止一个(例如颜色:红色、蓝色、绿色),则该函数在屏幕上仅打印数组的最后一个值
我阅读了文档,做了很多测试,并检查CSS是否没有问题。我也在StackOverflow和在线阅读了几乎所有关于这个问题的答案,但我找不到答案
是否有人可以帮助我了解错误在哪里?问题来自代码中的以下内容:
$terms = wp_get_post_terms( $product->get_id(), $taxonomy, array('fields' => 'names') );
foreach ( $terms as $term_name )
$term_names['names'] = $term_name;
$out .= implode(', ', $term_names);
您可以将其替换为以下内容:
$terms = wp_get_post_terms( $product->get_id(), $taxonomy, array('fields' => 'names') );
$term_names = []; // Initializing
// Loop through each terms
foreach ( $terms as $term_name ) {
$term_names[] = $term_name;
}
$out .= implode(', ', $term_names);
或者使用一行代码更好:
$out .= $product->get_attribute( $taxonomy );
更新。我编辑行
“$out.=内爆(”,“,$term\u names)代码>以这种方式$out.=内爆(',',$terms)现在它可以工作了(它跳过了foreach)。但我不确定我所做的是否正确。更新。下面我从@LoicTheAztec收到的答案清楚地解决了我的问题,也澄清了我的不确定性。我已经测试了您提出的两种解决方案,并确认它们都正确工作。特别是后者显然更便宜。你的回答清楚地回答了我的疑问,充其量也解决了我的问题。
$out .= $product->get_attribute( $taxonomy );