I need to generate xml file from all my products. My current query shows all product names, but how to access categories for each products? All the products have categories and subcategories. My current query:

$args = array( 
                'post_type' => 'product', 
                'orderby' => 'post_excerpt', 
                'order' => 'ASC',
                //'product_cat' => 'My Product Category',
                'post_status' => 'publish'
            $loop = new WP_Query( $args );

            while ( $loop->have_posts() ) {
                echo '' . get_the_title() . '<br /><br />';

1 Answer 1


You can use wp_get_post_terms()

$categories = wp_get_post_terms(get_the_ID(), 'product_cat', array("fields" => "names"));

The names of the product categories are returned as an array so you can either loop through them with a foreach or you can turn it into a string for example:

$categories_list = implode(",", $categories);

If you need more than just the names, you can get return array of the term properties by changing the fields to 'all'

$categories = wp_get_post_terms(get_the_ID(), 'product_cat', array("fields" => "all"));



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.