1

I'm trying to add a product archive widget in Elementor but in this widget specifically must hide "Out of stock" products.

I try to modify this code but I have not succeeded.

add_filter( 'woocommerce_product_query_meta_query', 'shop_only_instock_products', 10, 2 );
function shop_only_instock_products( $meta_query, $query ) {
    // Only on shop archive pages
    if( '#outst' ) return $meta_query;

    $meta_query[] = array(
        'key'     => '_stock_status',
        'value'   => 'outofstock',
        'compare' => '!='
    );
    return $meta_query;
}

Any ideas?

Sidebar of elementor:

Sidebar of Elementor

Product Widget Archive:
Product Widget Archive

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
SuperBad
  • 11
  • 2

1 Answers1

0

For widgets you should use woocommerce_products_widget_query_args hook instead. To hide Out of stock products, there is 2 ways:

1). With a meta query:

add_filter( 'woocommerce_products_widget_query_args', 'custom_products_widget_query_arg', 10, 1 );
function custom_products_widget_query_arg( $query_args ) {
    if( ! is_admin() ) {
        $query_args['meta_query'][] = array(
            'key'     => '_stock_status',
            'value'   => 'outofstock',
            'compare' => '!='
        );
    }
    return $query_args;
}

2). Or with a tax query:

add_filter( 'woocommerce_products_widget_query_args', 'custom_products_widget_query_arg', 10, 1 );
function custom_products_widget_query_arg( $query_args ) {
    if( ! is_admin() ) {
        $query_args['tax_query'][] = array(
            'taxonomy' => 'product_visibility',
            'field'    => 'name',
            'terms'    => array('outofstock'),
            'operator' => 'NOT IN'
        );
    }
    return $query_args;
}

Code goes in functions.php file of your active child theme (or active theme). Both could work.

Related:

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • how to make this code work for AJAX (Elementor)? I`m using "AJAX Products tabs" widget, on the first tab code is working, but on the other tabs isn't. – Acidburns Oct 18 '21 at 22:05