Question

i'm working on a small Woocommerce shop, and i would like to have a sorting function. The sorting works like a charm, but it is sorting based on the products class. So i would like to post the product category as class on the list item in my product loop. My loop looks like this:

<?php
    $args = array(
      'post_type' => 'product',
      'posts_per_page' => 999
      );
    $loop = new WP_Query( $args );
    if ( $loop->have_posts() ) {
        while ( $loop->have_posts() ) : $loop->the_post();
            woocommerce_get_template_part( 'content', 'product' );
        endwhile;
    } 
    else {
      echo __( 'No products found' );
    }
    wp_reset_postdata();
?>

It outputs list items for each item like this:

<li class="post-15 product type-product status-publish hentry first instock">
    <a href="http://shop.bbpixelz.dk/product/i-phone-ai-template/">
        <img width="150" height="150" src="http://shop.bbpixelz.dk/wp-content/uploads/2014/01/iphone-ai-template-150x150.png" class="attachment-shop_catalog wp-post-image" alt="iphone-ai-template">
        <h3>I-Phone Vector Template</h3>
    <span class="price"><span class="amount">$2</span></span>
    </a>
    <a href="/?add-to-cart=15" rel="nofollow" data-product_id="15" data-product_sku="ai-iphone" class="add_to_cart_button button product_type_simple">Add to cart</a>
</li>

I want to add the product category as a class to the li. How is this done?

Was it helpful?

Solution

Those classes are generated by the WordPress post_class() function as seen in the content-product.php template:

<li <?php post_class( $classes ); ?>>

There's a good example in the Codex on how to add categories to the post class. Modifying that a bit for product categories we have:

// add product category name to post class
function category_id_class( $classes ) {
    global $post;
    $product_cats = get_the_terms( $post->ID, 'product_cat' );
    if( $product_cats ) foreach ( $product_cats as $category ) {
        $classes[] = $category->name;
    }
    return $classes;
}
add_filter( 'post_class', 'category_id_class' );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top