Tuesday, July 16, 2024
WoocommerceWordpress Tricks

How to display products from specific product category with wordpress wp_query?

How to add custom meta title and meta description in Wordpress?

Display products from specific product category with wordpress wp_query

Hello, welcome to In this post, I will tell you, How to display products from specific product category with wordpress wp_query?  WordPress is the best cms. WordPress hooks(add_action, add_filter) give us the power to edit or change the code without interruption into the files and this is the best thing about wordpress. Now I am going to tell you how the hooks work.

Here is the working and tested code to display products from specific category with wordpress wp_query and with this query, we can get post with different category with the help of category slug name:

// Here you ca add your product category SLUG (can be multiple coma separated)
$product_categories = array('clothing');

$wc_query = new WP_Query( array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => 5,
    'tax_query' => array( array(
        'taxonomy' => 'product_cat',
        'field'    => 'slug',
        'terms'    => $product_categories,
        'operator' => 'IN',
    ) )
) );
     <?php if ($wc_query->have_posts()) : ?>
     <?php while ($wc_query->have_posts()) :
                $wc_query->the_post(); ?>
               <a href="<?php the_permalink(); ?>">
               <?php the_title(); ?>
          <?php the_post_thumbnail(); ?>
          <?php the_excerpt(); ?>
     <?php endwhile; ?>
     <?php wp_reset_postdata(); ?>
     <?php else:  ?>
          <?php _e( 'No Products' ); ?>
     <?php endif; ?>

 Now you are done and if you have query related to this post or you want to do some more with this code then please do comment below and I will come with wordpress hooks.


the authortherichpost
Hello to all. Welcome to Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.