1

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() ) {
                $loop->the_post();
                echo '' . get_the_title() . '<br /><br />';
            }
1

You can use wp_get_post_terms()

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

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

http://codex.wordpress.org/Function_Reference/wp_get_post_terms

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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