wp query - Woocommerce - exclude only older out-of-stock items

Trying to find a way to exclude out of stock items from listing, but only after some time (let's say, if they'

Trying to find a way to exclude out of stock items from listing, but only after some time (let's say, if they're older than one month).

I know I can exclude all of them easily, or change the order using something like this, but I'm looking for a something in-between... I guess using a pre_get_posts hook, but not sure about the specific query.

Any tips?

Trying to find a way to exclude out of stock items from listing, but only after some time (let's say, if they're older than one month).

I know I can exclude all of them easily, or change the order using something like this, but I'm looking for a something in-between... I guess using a pre_get_posts hook, but not sure about the specific query.

Any tips?

Share Improve this question edited Apr 23, 2019 at 23:01 Nicolai Grossherr 18.9k8 gold badges64 silver badges109 bronze badges asked Apr 22, 2019 at 15:39 Yoav AnerYoav Aner 3133 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

Most information necessary can be found at the Code Reference: WP_Query | Class . Otherwise useful resource Theme Handbook: Conditional Tags. Below code contains some clarifying comments. Please note, this is untested code, so no guarantees, but it should get you going.

add_action( 'woocommerce_product_query', 'custom_woocommerce_product_query' );
function custom_woocommerce_product_query( $q ) {
  if ( ! is_admin() ) {   
    //query for the out of stock items we want to exclude
    $oos_query = new WP_Query( [ 
      // items must be older than 1 month
      'date_query' => [ [ 
        'column' => 'post_date', 
        'before' => '1 month ago' 
      ], ],
      //only out of stock items...
      'meta_query' => [ [ 
        'key' => '_stock_status',
        'value' => 'outofstock',
        'compare' => '=',
       ], ],
      //we want products, nothing else
      'post_type' => 'product',
      //we want them all
      'posts_per_page' => -1,
      //the ids are enough, no need to get more data 
      'fields' => 'ids',
    ] );
    //getting array of ids from object
    $exclude_ids = $oos_query->posts;

    //excluding the above queried products from woocommerce's product query
    $q->set( 'post__not_in', $exclude_ids );
  }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745561592a4633136.html

相关推荐

  • wp query - Woocommerce - exclude only older out-of-stock items

    Trying to find a way to exclude out of stock items from listing, but only after some time (let's say, if they'

    7小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信