Woocommerce /如何按库存状态对相关产品进行排序?

时间:2019-02-26 16:58:24

标签: php wordpress function woocommerce

如何在woocommerce中按库存状态对相关产品进行排序?
我已将此代码添加到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 );
}


但是我想按库存状态在单个页面中对相关产品进行排序(先显示库存产品,然后显示缺货产品);
我已经像这样更改了$defaults数组:

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

它不起作用。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

尝试这些而不是您使用的

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

或者您可以在从数据库中获取过滤后的图像时,根据需要对它们进行排序。

相关问题