简体   繁体   English

Woocommerce /如何按库存状态分类相关产品?

[英]Woocommerce / how to sort related products by stock status?

How can I sort related products by stock status in woocommerce? 如何在woocommerce中按库存状态对相关产品进行排序?
I've added this code into function.php 我已将此代码添加到function.php

function custom_remove_hook(){
    remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products', 20 );
    add_action( 'woocommerce_after_single_product_summary', 'custom_function_to_sort_related', 22 );
}
add_action( 'woocommerce_after_single_product_summary', 'custom_remove_hook' );

function custom_function_to_sort_related( $args = array() ) {
    global $product;

    if ( ! $product ) {
        return;
    }

    $defaults = array(
        'posts_per_page' => 4,
        'columns'        => 4,
        'orderby'        => 'price', // @codingStandardsIgnoreLine.
        'order'          => 'desc'
    );

    $args = wp_parse_args( $args, $defaults );

    // Get visible related products then sort them at random.
    $args['related_products'] = array_filter( array_map( 'wc_get_product', wc_get_related_products( $product->get_id(), $args['posts_per_page'], $product->get_upsell_ids() ) ), 'wc_products_array_filter_visible' );

    // Handle orderby.
    $args['related_products'] = wc_products_array_orderby( $args['related_products'], $args['orderby'], $args['order'] );

    // Set global loop values.
    wc_set_loop_prop( 'name', 'related' );
    wc_set_loop_prop( 'columns', apply_filters( 'woocommerce_related_products_columns', $args['columns'] ) );

    wc_get_template( 'single-product/related.php', $args );
}


But I'd like to sort related products in single page by stock status (First show instock products then out of stock products); 但是我想按库存状态在单页中对相关产品进行排序(首先显示库存产品,然后显示缺货产品);
I've changed $defaults array like this: 我已经更改了$defaults数组,如下所示:

$defaults = array(
        'posts_per_page' => 4,
        'columns'        => 4,
        'orderby'        => '_stock_status', 
        'order'          => 'array( 'meta_value' => 'ASC' )
    );

It doesn't work. 没用 How can I solve this problem? 我怎么解决这个问题?

Try these instead of the one you used 尝试这些而不是您曾经使用过的

$defaults = array(
            'posts_per_page' => 4,
            'columns'        => 4,
            'orderby'        => array('price', 'stock')
            'order'          => 'desc'
        );

or you can just sort the filtered images as per your requirement while fetching it from the database. 或者,您也可以根据需要对过滤的图像进行排序,同时从数据库中获取图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM