Add sorting by stock quantity in WooCommerce products sort by

我的梦境 提交于 2021-02-04 21:42:36

问题


I have added the following code to my theme functions.php.

The "Availability" sort option does show up but when I select it, it is sorted by Title, not stock quantity.

I also tried using stock_quantity as a meta_key (even though it's not a meta) and that didn't work either.

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );
function custom_woocommerce_get_catalog_ordering_args( $args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'availability' == $orderby_value ) {
        $args['orderby'] = 'stock_quantity';
        $args['order'] = 'DESC';
        $args['meta_key'] = '';
    }
    return $args;
}

add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );
function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['availability'] = 'Availability';
    return $sortby;
}

回答1:


Use ['meta_key'] = '_stock' & ['orderby'] = 'meta_value_num'

// Add custom sorting options
function filter_woocommerce_get_catalog_ordering_args( $args ) {
    $orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( $orderby_value == 'availability' ) {
        $args['orderby'] = 'meta_value_num';
        $args['order'] = 'DESC';
        $args['meta_key'] = '_stock';
    }
    return $args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'filter_woocommerce_get_catalog_ordering_args', 10, 1 );   

function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['availability'] = 'Availability';
    return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby', 10, 1 );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby', 10, 1 );

// Optional: use for debug purposes (display stock quantity) 
function action_woocommerce_after_shop_loop_item() {
    global $product;
    echo wc_get_stock_html( $product );
}
add_action( 'woocommerce_after_shop_loop_item', 'action_woocommerce_after_shop_loop_item', 10, 0 );


来源:https://stackoverflow.com/questions/62353002/add-sorting-by-stock-quantity-in-woocommerce-products-sort-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!