TiboK
TiboK

Reputation: 95

Woocommerce URL to hide out of stock product

I create a catalog website using Woocommerce to display all the product. When the product is sell, i dont remove it from the website (because we dont have a lot of product and we want to show to the customer what we sell before).

So, when you go on "All the products" you see the Sell products and the products available. I want, on the sidebar create a button "Show only available product". I dont find a plugin who can do this..

Whis woocommerce, can i create a URL like "mywebsite.com/products&instock=true" for example or something like this ? or if you know another solution. Thanks

Upvotes: 0

Views: 662

Answers (1)

Alexis Vandepitte
Alexis Vandepitte

Reputation: 2088

You can use pre_get_posts to achieve it. Set the tax_query to not get the term outofstock of the product_visibility taxonomy.

In addition to my code, you will of course need to create a link with the prefix_instock=true parameter. You also can store it in a cookie, so it will be easily persistent.

add_action( 'pre_get_posts', 'prefix_hide_out_of_stock_products' );
function prefix_hide_out_of_stock_products( $q ) {

    if ( ! $q->is_main_query() || is_admin() || empty($_GET['prefix_instock'])) {
        return;
    }

    if ( $outofstock_term = get_term_by( 'name', 'outofstock', 'product_visibility' ) && $_GET['prefix_instock'] == 'true') {

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

        $tax_query[] = array(
            'taxonomy' => 'product_visibility',
            'field' => 'term_taxonomy_id',
            'terms' => array( $outofstock_term->term_taxonomy_id ),
            'operator' => 'NOT IN'
        );

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

    }

    remove_action( 'pre_get_posts', 'prefix_hide_out_of_stock_products' );

}

Upvotes: 0

Related Questions