Fran Cano
Fran Cano

Reputation: 725

Woocommerce - Display categories within the loop

Is it posible to display the product categories right beneath the tile, within the WooCommerce loop?

Here's a code that I've included in mytheme/woocommerce/content-product.php, taken from the Wordpress documentation on get_the_category(); yet it doesn't seem to output anything at all

        <a href="<?php the_permalink(); ?>" class="titulo-insumo" title="<?php the_title(); ?>">
            <?php the_title(); ?>
        </a>
        <div class="label-group"><!--Categories *should* be outputed here -->
        <?php
        $categories = get_the_category();
        $separator = ' ';
        $output = '';
        if($categories){
                foreach($categories as $category) {
                        $output .= '<a href="'.get_category_link( $category->term_id ).'" class="label bg-terciary" title="' . esc_attr( sprintf( __( "Ver todos los artículos en la categoría %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
                }
        echo trim($output, $separator);
        }

        ?>

        </div>

Upvotes: 2

Views: 7012

Answers (1)

Fran Cano
Fran Cano

Reputation: 725

Well, it didn't took much to figure out, so I'm posting my result here. The category is outputed using the get_the_terms() wordpress function and the link is outputed with a simple get request (/?product_cat=), wich I assume will not work for any kind of pretty permalinks option enabled

<?php
        $terms = get_the_terms( $post->ID, 'product_cat' );

        if ( $terms && ! is_wp_error( $terms ) ) : //only displayed if the product has at least one category

                $cat_links = array();

                foreach ( $terms as $term ) {
                        $cat_links[] = '<a class="label bg-terciary" href="'.get_site_url().'/?product_cat='.$term->slug.'" title="'.$term->name.'">'.$term->name.'</a>';
                }

                $on_cat = join( " ", $cat_links );
        ?>

        <div class="label-group">
            <?php echo $on_cat; ?>
        </div>

        <?php endif; ?>

Upvotes: 2

Related Questions