0

I'm trying to get or list all category names or IDs of the current product in WooCommerce.
Using this code: I get whole links to the categories but I want their names or IDs.

<?php
    // Get list of ALL categories for current product
    $cats = wc_get_product_category_list( $id );

    var_dump($cats);
?> 

I want categories' names or IDs so I can use them to iterate through.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Kerim Tim.
  • 1,159
  • 12
  • 13

2 Answers2

2

Pase the following code in the functions.php file of the theme.

add_action( 'init', function() {
    $categories = wp_get_post_terms( 17, 'product_cat' );
    if ( ! empty( $categories ) ) {
        $html = '<ul>';
        foreach( $categories as $category ) {
            $html .= "<li>{$category->name}</li>";
        }
        $html .= '</ul>';
    }

    echo $html;
    die;
});

Reference: https://developer.wordpress.org/reference/functions/wp_get_post_terms/

Sagar Bahadur Tamang
  • 2,670
  • 2
  • 24
  • 41
1
// Get list of ALL categories for current product
$term_ids = array();
$terms = get_the_terms( 158, "product_cat" );
if(!is_wp_error( $terms )){
    foreach ( $terms as $term ) {
        $term_ids[] = $term->term_id;
    }
}

var_dump($term_ids);exit;

Try this

mujuonly
  • 11,370
  • 5
  • 45
  • 75