WooCommerce 产品在循环问题中自定义附加分类法

WooCommerce product custom additional taxonomy in a loop issue

我正在尝试循环显示单个产品的自定义分类字段名称和描述。

我已经创建了自定义产品分类法

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
}}
?>

但有一个问题我无法解决:

Warning: foreach() argument must be of type array|object, bool given in

我做错了什么?

更新 (与您的评论相关)

您需要在上一个函数之前检查 $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' ) ) {