【发布时间】:2021-03-09 12:49:00
【问题描述】:
我正在尝试循环显示单个产品的自定义分类字段的名称和描述。
我创建了自定义产品分类
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() 参数必须是数组|对象类型,在
我做错了什么?
【问题讨论】:
-
这意味着您从
get_terms返回了一个布尔值,并且正如文档所解释的那样,如果没有为帖子分配术语,就会出现这种情况。 developer.wordpress.org/reference/functions/get_the_terms
标签: php wordpress woocommerce advanced-custom-fields taxonomy-terms