S
S
Sergei Gurdjiyan2018-07-19 13:59:19
WooCommerce
Sergei Gurdjiyan, 2018-07-19 13:59:19

How to add custom sorting in Woocommerce?

You need to add two fields to the default sort select:
- sorting by Sales - Displaying products with a discount price
- sorting New - displaying products that have an ACF field (checkbox field) new with a value of true
I added the necessary items in the select without problems, I use it for sorting the code:

add_filter('woocommerce_get_catalog_ordering_args', 'wcs_get_catalog_ordering_args');
    function wcs_get_catalog_ordering_args($args)
    {
        $orderby_value = isset($_GET['orderby']) ? woocommerce_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby'));
        if ('sales' === $orderby_value) {
            $args['orderby'] = 'meta_value_num';
            $args['order'] = 'DESC';
            $args['meta_key'] = '_sale_price';
            $args['meta_query'] = array(
                array(
                    'key' => '_sale_price',
                    'value' => 0,
                    'compare' => '>',
                    'type'    => 'NUMERIC',
                )
            );
        }
        if ('new' === $orderby_value) {
            $args['orderby'] = 'meta_value';
            $args['order'] = 'DESC';
            $args['meta_key'] = 'new';
            $args['meta_query'] = array(
                array(
                    'key' => 'new',
                    'value' => 1,
                    'compare' => '=',
                )
            );
        }
        return $args;
    }

When sorting New, the goods are sorted, the fields with New are immediately displayed, after the rest. And you need to exclude other products altogether.
Sorting by sales doesn't work at all.
How to add your own sorting?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2018-07-19
@pton

And you need to exclude other products altogether.

If goods need to be excluded, then this is filtering and not sorting!
Although this code will display all records that have a meta field by which sorting is performed in the specified sequence. This means that if some of the records do not have the specified meta field (note that the phrase "will not have" means the absence of such a meta field, and not its empty value), then this record will not be included in the selection and will not be displayed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question