Kenshinh
Kenshinh

Reputation: 173

Get woocommerce product tag slugs as an array

How to get woocommerce tag slug names to an array correctly? I'm using the following code but it doesn't output anything.

    <?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);

    ?>

Upvotes: 2

Views: 1736

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

You could use wp_get_post_terms() WordPress function instead this way to get the term slugs in an array with one line of code

$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>'; 

Upvotes: 3

Related Questions