How to Display Product specific to a category with WooCommerce Plugin?

  • I'm using plugin Woocommerce to do shop online.

    I have many categories for example shoes, clothes and so on. How can I display the products of specific category?

    I see such product loops of on the sample page, but I only want show the products of a specific category in my index.php.

    can u please tell me where to add this code if you please

  • dwaser

    dwaser Correct answer

    8 years ago

    You need to create a new loop for that. Here's the code I use for displaying products from a specific category on the home page:

    <ul class="products">
            $args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product_cat' => 'shoes', 'orderby' => 'rand' );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
                    <li class="product">    
                        <a href="<?php echo get_permalink( $loop->post->ID ) ?>" title="<?php echo esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID); ?>">
                            <?php woocommerce_show_product_sale_flash( $post, $product ); ?>
                            <?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); else echo '<img src="'.woocommerce_placeholder_img_src().'" alt="Placeholder" width="300px" height="300px" />'; ?>
                            <h3><?php the_title(); ?></h3>
                            <span class="price"><?php echo $product->get_price_html(); ?></span>                    
                        <?php woocommerce_template_loop_add_to_cart( $loop->post, $product ); ?>
        <?php endwhile; ?>
        <?php wp_reset_query(); ?>

    @VanTong Then mark this answer as **the answer:** click the checkmark on the left side.

    Hi Dwaser,I want ask more. If in archive page, I want show all new product. and When I choose specific Category It will show product of that category. Example I have 2 category Category A and Category B,When I choose A, it will show product of A, and choose B it will show product of B. Please tell me loops. thanks.

    hot show message if there is no products?

    @dwaser Hi, deos the product_cat argument accept an int category id, ie: 40 instead of 'shoes' ? if not, how to make it accept an int category id ? thanks

    @dwaser. looks like that function woocommerce_placeholder_img_src() has been deprecated now. Would get_image() be the equivalent? Also, why do you check for a post thumbnail first?

    exicuse me guys, but where to add this code ? i'm a newpie in wordpress but i have a very close deadline. @VanTong

    I am also wondering about the context of this code. Where to put it?

    1 year late, but you should put this in your template. wp-content/yourtheme/template-name.php

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM