skip to Main Content

I’m trying to pull all products located within a certain category slug.

I’ve tried the following, however both return every product in the store.

$products = wc_get_products( array( 'category' => array( 'Sony' ) ));

and

$productlist = wp_query(array( 'post_type' => 'product', 'product_cat' => 'Sony'));

Any pointers would be much appreciated.

3

Answers


  1. Try this code

    $args = array(
    'post_type'      => 'product',
    'posts_per_page' => -1,
    'tax_query'      => array(
        array(
            'taxonomy' => 'category',
            'terms'    => 12,// category ID
        ),
    ),
    );
    
    Login or Signup to reply.
  2. Try This:

     <?php
        $args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'product_cat' => 'Sony', 'orderby' => 'rand' );
        $data = new WP_Query( $args );
    print_r($data);
    
    Login or Signup to reply.
  3. Try with this and replace ENTER_CATEGORY with slug name or use simple ‘terms’ => ‘slug/categoryname’

    $args = array(
            'post_type'             => 'product',
            'post_status'           => 'publish',
            'tax_query'             => array(
                array(
                    'taxonomy'      => 'product_cat',
                    'terms'         => array_map( 'sanitize_title', explode( ',', 'ENTER_CATEGORY' ) ),
                    'field'         => 'slug',
                    'operator'      => $atts['operator']
                )
            )
        );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search