'Woocommerce product admin sort by stock

Is there anyway I can sort by stock? Since it reads 'Stock x 30' it would be helpful if I could sort by high or low. Is there any code I can add to the functions.php to enable that feature?



Solution 1:[1]

easy enough... it can be accomplished with this code...

add_filter( 'manage_edit-product_sortable_columns', 'rei_product_sortable_columns' );
function rei_product_sortable_columns( $columns ) {
    $custom = array(
        'is_in_stock' => 'is_in_stock'
    );
    return wp_parse_args( $custom, $columns );
}

but this would just sort what the stock column has... example, 'in stock' or 'out of stock'


To have a custom sort, (for example, using the stock number), you may follow the instruction on this blog post.

Solution 2:[2]

Working version as of: Year 2022, WP 5.9.3, WC 6.4.1:

// make quantity column sortable
function rei_product_sortable_columns( $columns )
{
    $custom = array(
        'is_in_stock' => 'stock_disponible'
    );
    return wp_parse_args( $custom, $columns );
}
add_filter( 'manage_edit-product_sortable_columns', 'rei_product_sortable_columns' );

// only load on edit.php page
function my_edit_movie_load() {
    add_filter( 'request', 'my_sort_movies' );
}
add_action( 'load-edit.php', 'my_edit_movie_load' );

// do the sorting
function my_sort_movies( $vars )
{
    /* Check if we're viewing the 'product' post type. */
    if ( isset( $vars['post_type'] ) && 'product' == $vars['post_type'] )
    {
        /* Check if 'orderby' is set to 'stock_disponible'. */
        if ( isset( $vars['orderby'] ) && 'stock_disponible' == $vars['orderby'] )
        {
            /* Merge the query vars with our custom variables. */
            $vars = array_merge(
                $vars,
                array(
                    'meta_key' => '_stock',
                    'orderby' => 'meta_value_num'
                )
            );
        }
    }

    return $vars;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Lolo