Mike
Mike

Reputation: 117

How to sort products in category by post id in WooCommerce?

In shop, some products belong to multiple categories. This makes default WooCommerce ordering not working, because if one product is first in category A then other product can't be first in category B if both belong to the same category.

I want to find a way to sort products in shop categories by post id in particular order I want ( I will supply IDs).

So far I came up with:

add_filter( 'woocommerce_get_catalog_ordering_args', 'my_ordering_function', 20, 1 );
function my_ordering_function( $args ) {

    $product_category = 'my-category'; 

    if( ! is_product_category($product_category) ) return $args;

    $args['post__in'] = array( 74, 116, 3565, 3563 );
    $args['orderby'] = 'post__in';
    $args['order'] = 'ASC';

    return $args;
}

This code should do the job, but after examining woocommerce_get_catalog_ordering_args source code, it looks like post__in is not even supported.

Any ideas on how to dictate my own product order per category?

Upvotes: 2

Views: 1679

Answers (1)

Shahbaz A.
Shahbaz A.

Reputation: 4356

With your approach, you can do this in the parent function of the function that uses the woocommerce_get_catalog_ordering_args filter.

The function you are looking for is product_query, in this function you have an action hook woocommerce_product_query. For your use case, something like this would work.

function my_ordering_function( $q, $this ) {
    $q->set( 'post__in', array( 74, 116, 3565, 3563 ) );
    $q->set( 'orderby', 'post__in' );
}
add_action( 'woocommerce_product_query', 'my_ordering_function', 10, 2 );

P.S. This function is also in the same file that you referenced. You can have a look there to see how it works.

Upvotes: 1

Related Questions