skip to Main Content

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.

2

Answers


  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

    Login or Signup to reply.
  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/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search