Frithir.com
Frithir.com

Reputation: 295

Woocommerce sort ASC and DESC based on category

I trying to sort products based on categories.

If Product category A and sub-categories sort ASC

Else if Product category B and sub-categories sort DESC.

In functions.php

add_filter('woocommerce_get_catalog_ordering_args', 'am_woocommerce_catalog_orderby');
function am_woocommerce_catalog_orderby( $args ) {

$args['meta_key'] = 'countdown_date';

$args['orderby'] = 'meta_value';

// need an if statement here to switch the order

$args['order'] = 'DESC';         

return $args;
}

Upvotes: 4

Views: 1662

Answers (1)

Domain
Domain

Reputation: 11808

You can use following code to solve your purpose:

function wdm_change_ordering($args)
{
    if (is_product_category()) {
        global $wp_query;
        $cat = $wp_query->get_queried_object();

        $category_A_term_id = 53;
        $category_B_term_id = 2;

        if (!empty($cat) && ($cat->term_id === $category_A_term_id || $cat->parent === $category_A_term_id)) {
            $args['order'] = 'ASC';
        } elseif (!empty($cat) && ($cat->term_id === $category_B_term_id || $cat->parent === $category_B_term_id)) {
            $args['order'] = 'DESC';
        }
    }
    return $args;
}
add_filter('woocommerce_get_catalog_ordering_args', 'wdm_change_ordering', 10, 1);

Remember to change $category_A_term_id & $category_B_term_id variable values to corresponding category ids.

Above code will check, if current is category archive page and if it is, category A or child of category A, change order, similarly for category B.

Alternatively, you can also use following WooCommerce condition:

is_product_category( array( 'shirts', 'games' ) )

but, here all categories must be specified.

Upvotes: 2

Related Questions