0
votes

How can I sort related products by stock status in woocommerce?
I've added this code into 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 = 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?

1

1 Answers

0
votes

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.