简体   繁体   中英

Using tax_query to filter posts to all products that are in stock and those out of stock of a particular category

Here is the current code that I have tested:

add_action( 'pre_get_posts', 'iconic_hide_out_of_stock_products' );

function iconic_hide_out_of_stock_products( $q ) {

//if in admin mode, leave function
if ( ! $q->is_main_query() || is_admin() ) {
    return;
}


// get term name, 'outofstock', in Product Visibility Taxonomy
if ( $outofstock_term = get_term_by( 'name', 'outofstock', 'product_visibility' ) ) {

    $tax_query = (array) $q->get('tax_query');

    $tax_query[] = array(
        'post_type' => 'post',
        'tax_query' =>array(
            'relation' => 'OR',
            array( //get all products that are in stock 
                'taxonomy' => 'product_visibility',
                'field' => 'term_taxonomy_id',
                'terms' => array( $outofstock_term->term_taxonomy_id ),
                'operator' => 'NOT IN',
            ),
            array( //show these products even if they are out of stack
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => array( 'category-name' ),
            ),
        ),
    );

    $q->set( 'tax_query', $tax_query );

}


remove_action( 'pre_get_posts', 'iconic_hide_out_of_stock_products' );

}

Im not sure if im using the $tax_query right, I assumed by using the 'or' relation I should be getting a return of all in stock products and out of stock products of the specified category.

I also have tried using 'and' as the relation with no better results.

OK, I think you may be able to use a nested tax_query ... something like below:

'tax_query' => array(
  // I think you need AND here. can omit as it is the default.
  'relation' => 'AND',

  // get all products that are in stock. this should include
  // all products in "some_cat" that are in stock
  array(
    'taxonomy' => 'product_visibility',
    'field' => 'term_taxonomy_id',
    'terms' => array( $outofstock_term->term_taxonomy_id ),
    'operator' => 'NOT IN',
  ),

  // AND...

  array(
    // AND is the default but I added it here for brevity
    'relation' => 'AND',

    // show products in "some_cat"
    array( 
        'taxonomy' => 'product_cat',
        'field' => 'slug',
        'terms' => array( 'some_cat' ),
    ),

    // even if they are out of stock
    array(
      'taxonomy' => 'product_visibility',
      'field' => 'term_taxonomy_id',
      'terms' => array( $outofstock_term->term_taxonomy_id ),
      'operator' => 'NOT IN',
    ),
  )
),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM