Get WooCommerce Subscription product type and specific category in a WP_Query

Viewed 667

I'm using the WooCommerce Subscriptions plug-in for several products in the catalog that are available as both individual or subscription products and am writing a custom template page to query products that are available as subscriptions. My query is below, everything looks right to my eyes, but for some reason it's not working. Can anyone see what's wrong here?

*Note, if I remove the 'tax_query', all the coffee products are returned as expected, but when I try to restrict by the tax_query no products are returned (and yes, I have subscription products in the coffee category).

$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'product_cat' => 'coffee',
    'tax_query' => array( // builds the taxonomy query
            array(
                'taxonomy' => 'product_type',
                'field'    => 'name',
                'terms'    => 'subscription',
            ),
        ),
    );
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
    while ( $loop->have_posts() ) : $loop->the_post();
        wc_get_template_part( 'content', 'product' );
    endwhile;
} else {
    echo __( 'No products found' );
}
wp_reset_postdata();
1 Answers

You need to make a "tax_query" for the product category too, to avoid this problem as the way you are doing it, is deprecated since WordPress version 3.1 in favor of "tax_query". So in your code:

$loop = new WP_Query( array(
    'post_type'      => 'product',
    'posts_per_page' => -1,
    'post_status'    => 'publish',
    'tax_query'      => array( // builds the taxonomy query
        'relation' => 'AND',
        array(
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => 'coffee',
        ),
        array(
            'taxonomy' => 'product_type',
            'field'    => 'name',
            'terms'    => 'subscription',
        ) 
    )
) );

if ( $loop->have_posts() ) {
    while ( $loop->have_posts() ) : $loop->the_post();
        wc_get_template_part( 'content', 'product' );
    endwhile;
} else {
    echo __( 'No products found' );
}

wp_reset_postdata();

It should work.

Related