在 WooCommerce 产品排序中添加按库存数量排序

我已将以下代码添加到我的主题中functions.php。


“可用性”排序选项确实显示,但当我选择它时,它是按标题排序的,而不是库存数量。


我也尝试过使用stock_quantityas a meta_key(即使它不是元),但也没有用。


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;

}


素胚勾勒不出你
浏览 131回答 1
1回答

拉莫斯之舞

最后更新:02/22 - 在 WordPress 5.9.1 和 WooCommerce 6.1.1 中测试代码进入活动子主题(或活动主题)的 functions.php 文件。使用['meta_key'] = '_stock'&['orderby'] = 'meta_value_num'代替所以你得到:// Ordering products based on the selected valuesfunction filter_woocommerce_get_catalog_ordering_args( $args, $orderby, $order ) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; switch( $orderby ) {&nbsp; &nbsp; &nbsp; &nbsp; case 'availability':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $args['orderby']&nbsp; = 'meta_value_num';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $args['order']&nbsp; &nbsp; = 'DESC';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $args['meta_key'] = '_stock';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; return $args;}add_filter( 'woocommerce_get_catalog_ordering_args', 'filter_woocommerce_get_catalog_ordering_args', 10, 3 );// Orderby settingfunction filter_orderby( $orderby ) {&nbsp; &nbsp; $orderby['availability'] = __( 'Availability', 'woocommerce' );&nbsp; &nbsp; 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)&nbsp;function action_woocommerce_after_shop_loop_item() {&nbsp; &nbsp; global $product;&nbsp; &nbsp; 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 );
打开App,查看更多内容
随时随地看视频慕课网APP