wp-content » themes » functions.php » Create Stock Filter in WooCommerce – Sort products by Availability

Create Stock Filter in WooCommerce – Sort products by Availability

This code snippet will create a new Filter option for WooCommerce: Availability that will allow users to sort products based on stock number.

image 15 1024x416 - Create Stock Filter in WooCommerce - Sort products by Availability

Add the code to your active theme functions.php or create a new Child theme first to make sure that your edits are not deleted after theme update.

// Ordering products based on the selected values
function filter_woocommerce_get_catalog_ordering_args( $args, $orderby, $order ) {    
    switch( $orderby ) {
        case 'availability':
            $args['orderby']  = 'meta_value_num';
            $args['order']    = 'DESC';
            $args['meta_key'] = '_stock';
            break;
    }
    return $args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'filter_woocommerce_get_catalog_ordering_args', 10, 3 );

// Orderby setting
function filter_orderby( $orderby ) {
    $orderby['availability'] = __( 'Availability', 'woocommerce' );
    return $orderby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'filter_orderby', 10, 1 );
add_filter( 'woocommerce_catalog_orderby', 'filter_orderby', 10, 1 );

// Optional: use for debug purposes (display stock quantity) 
function action_woocommerce_after_shop_loop_item() {
    global $product;
    echo '<div style="color: red !important; font-size: 20px !important;">' . wc_get_stock_html( $product ) . '</div>';
}

add_action( 'woocommerce_after_shop_loop_item', 'action_woocommerce_after_shop_loop_item', 9, 0 );
See also  Display all Active WordPress plugins

Was this post helpful?

Leave a Comment

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.

Recommended