Php WooCommerce产品自定义循环中的附加分类问题
我试图在一个循环中显示单个产品的自定义分类字段的名称和描述 我已经创建了自定义产品分类法Php WooCommerce产品自定义循环中的附加分类问题,php,wordpress,woocommerce,advanced-custom-fields,taxonomy-terms,Php,Wordpress,Woocommerce,Advanced Custom Fields,Taxonomy Terms,我试图在一个循环中显示单个产品的自定义分类字段的名称和描述 我已经创建了自定义产品分类法 add_action( 'init', 'create_distinctions_nonhierarchical_taxonomy', 0 ); function create_distinctions_nonhierarchical_taxonomy() { // Labels part for the GUI $labels = array( 'name' => _x( '
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' ),
));
}
下一步创建的示例标记:1、2,并将它们分配给产品(通过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()参数的类型必须为array | object,bool在中给出
我做错了什么?更新(与您的评论相关)
在上一个函数中,您需要检查$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
}
}
}
}
与:
这意味着您从
get_terms
返回了一个布尔值,正如文档中所解释的,如果没有为帖子分配任何术语,则会出现这种情况。嗯,部分。这里还有另一个警告:警告:尝试读取数组[…]上的属性“名称”警告:尝试读取数组[…]上的属性“说明”
if ( term_exists( $term, $taxonomy ) ) {
if ( is_a( $term, 'WP_Term' ) ) {