user7925528
user7925528

Reputation:

Woocommerce, get products by category with wp query

I tried many methods, but I can't show products with category name or id

                  $args = array(
                       'post_type'             => 'product',
                       'post_status'           => 'publish',
                       'ignore_sticky_posts'   => 1,
                       'cat'                   => 40,
                       'posts_per_page'        => '12',
                   );

                  $loop = new WP_Query( $args );

Upvotes: 3

Views: 30138

Answers (4)

Dipak Kumar Pusti
Dipak Kumar Pusti

Reputation: 1723

Try tax_query

$args = array(
   'post_type'             => 'product',
   'post_status'           => 'publish',
   'ignore_sticky_posts'   => 1,
   'posts_per_page'        => '12',
   'tax_query'             => array(
        array(
            'taxonomy'  => 'product_cat',
            'field'     => 'term_id',
            'terms'     => array('40'),
            'operator'  => 'IN',
        )
   )
);

$loop = new WP_Query( $args );

https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

Upvotes: 2

felix manzanas
felix manzanas

Reputation: 119

I suggest used >> wc_get_product_terms( $vars->ID, 'pa_brand_category' )

please check this screenshot >> http://prntscr.com/hjawu5

Upvotes: -1

Priyanka Modi
Priyanka Modi

Reputation: 1624

Try this example,

So given a category with ID 26, the following code would return it's products (WooCommerce 3+):

 $args = array(
    'post_type'             => 'product',
    'post_status'           => 'publish',
    'ignore_sticky_posts'   => 1,
    'posts_per_page'        => '12',
    'tax_query'             => array(
        array(
            'taxonomy'      => 'product_cat',
            'field' => 'term_id', //This is optional, as it defaults to 'term_id'
            'terms'         => 26,
            'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
        ),
        array(
            'taxonomy'      => 'product_visibility',
            'field'         => 'slug',
            'terms'         => 'exclude-from-catalog', // Possibly 'exclude-from-search' too
            'operator'      => 'NOT IN'
        )
    )
);
$products = new WP_Query($args);
var_dump($products);

Upvotes: 9

Sunil Dora
Sunil Dora

Reputation: 1472

Try this,

<?php
  $args     = array( 'post_type' => 'product', 'post_status' => 'publish','category' => 34, 'ignore_sticky_posts' => 1, 'posts_per_page' => '12',);
  $products = get_posts( $args ); 
?>

Hope this will helps you. for more info.

Upvotes: 0

Related Questions