如何解决WooCommerce 产品自定义附加分类法循环问题
我正在尝试在循环中显示单个产品的自定义分类字段的名称和描述。
我创建了自定义产品分类
add_action( 'init','create_distinctions_nonhierarchical_taxonomy',0 );
function create_distinctions_nonhierarchical_taxonomy() {
// Labels part for the GUI
$labels = array(
'name' => _x( 'Distinction','taxonomy general name' ),'singular_name' => _x( 'Distinction','taxonomy singular name' ),'search_items' => __( 'Search Distinction' ),'popular_items' => __( 'Popular Distinction' ),'all_items' => __( 'All Distinction' ),'parent_item' => null,'parent_item_colon' => null,'edit_item' => __( 'Edit Distinction' ),'update_item' => __( 'Update Distinction' ),'add_new_item' => __( 'Add New Distinction' ),'new_item_name' => __( 'New Distinction Name' ),'separate_items_with_commas' => __( 'Separate distinctions with commas' ),'add_or_remove_items' => __( 'Add or remove distinctions' ),'choose_from_most_used' => __( 'Choose from the most used distinctions' ),'menu_name' => __( 'Distinctions' ),);
// Now register the non-hierarchical taxonomy like tag
register_taxonomy('distinctions',array('product'),array(
'hierarchical' => false,'labels' => $labels,'show_ui' => true,'show_in_rest' => true,'show_admin_column' => true,'update_count_callback' => '_update_post_term_count','query_var' => true,'rewrite' => array( 'slug' => 'distinctions' ),));
}
接下来创建的示例标签:一、二并将它们分配给产品(通过 ACF 插件)
我希望它们显示在产品页面上。我试图使用此代码:
<?php
add_action( 'woocommerce_product_meta_end','action_product_meta_end' );
function action_product_meta_end() {
global $post;
$terms = get_the_terms( $post->ID,'distinctions' );
foreach ( $terms as $term ) {
?>
<ul>
<li>
<h5><?php echo $term->name; ?></h5>
<p><?php echo $term->description; ?></p>
</li>
</ul>
<?php
}}
?>
但是有一个我无法解决的问题:
警告:foreach() 参数的类型必须是数组|对象,在中给出的布尔值
我做错了什么?
解决方法
更新 (与您的评论有关)
您需要在最后一个函数中检查 $terms
变量之前不为空,并且每个术语都存在,例如:
add_action( 'woocommerce_product_meta_end','action_product_meta_end' );
function action_product_meta_end() {
global $post;
$taxonomy = 'distinction';
$terms = get_the_terms( $post->ID,$taxonomy );
if ( $terms && ! empty( $terms ) ) {
foreach ( $terms as $term ) {
if ( term_exists( $term,$taxonomy ) ) {
?>
<ul>
<li>
<h5><?php echo $term->name; ?></h5>
<p><?php echo $term->description; ?></p>
</li>
</ul>
<?php
}
}
}
}
这应该可以解决问题。
如果您的其他问题仍然存在,您也可以尝试从我的代码中替换:
if ( term_exists( $term,$taxonomy ) ) {
与:
if ( is_a( $term,'WP_Term' ) ) {
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。