将 woocommerce 产品标签块作为数组获取

Get woocommerce product tag slugs as an array

如何正确地将 woocommerce 标签 slug 名称获取到数组?我正在使用以下代码,但它没有输出任何内容。

    <?php 

$terms = get_the_terms( $post->ID, 'product_tag' );

        $sluglist = array();
        if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
            foreach ( $terms as $term ) {
                $sluglist[] = $term->slug;
            }
        }

    echo count($sluglist);

    ?>

您可以改用 wp_get_post_terms() WordPress 函数,用一行代码在数组中获取术语 slugs

$term_slugs = wp_get_post_terms( get_the_id(), 'product_tag', array( 'fields' => 'slugs' ) );

// The term slugs count
echo count($term_slugs);

// Testing: The raw output (preformatted)
echo '<pre>'; print_r($term_slugs); echo '</pre>';