Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query / Filter woocommerce products by product type

I added new product type like here

Now I want to show just that product type. Here is the my query:

$query_args = array('post_type' => 'product' );

$r = new WP_Query( $query_args );

if ( $r->have_posts() ) { .........

How can I query only products of this new product type?

like image 970
trikutin Avatar asked Apr 22 '15 17:04

trikutin


2 Answers

In WooCommerce, "post type" is a custom taxonomy, so you need to add taxonomy parameters to WP_Query.

$query_args = array(
   'post_type' => 'product',
   'tax_query' => array(
        array(
            'taxonomy' => 'product_type',
            'field'    => 'slug',
            'terms'    => 'your_type', 
        ),
    ),
 );

Where the terms argument is the same as in the $this->product_type = 'your_type'; part of your new product type's class constructor.

like image 159
helgatheviking Avatar answered Oct 30 '22 22:10

helgatheviking


A cleaner way - use WooCommerce wc_get_products rather than just WP_Query.

$args = array(
    'type' => 'custom_product_type'
    );
$products = wc_get_products( $args );
like image 38
MegPhillips91 Avatar answered Oct 30 '22 23:10

MegPhillips91