Hassan
Hassan

Reputation: 33

WooCommerce Order By Price Not Working Correctly

When slecting the option sort by price (Woocommerce dropdown) the products to sort in price but it's not working exactly; the first 6 are sorted:

Link to unfinished website: http://verduijncichlids.com/product-categorie/vissen-voorraad/west-afrika-cichliden/?orderby=price

Anyone know what is happening and how to fix this? Cheers!

Upvotes: 3

Views: 18579

Answers (5)

Jannick
Jannick

Reputation: 81

If ordering by price is not working correctly in WooCommerce a secure solution is always to customize how WooCommerce handles the ordering by price. This works because WooCommerce price and price-desc are default ordering options. (Tested with standard theme in WordPress v5.4.1 & WooCommerce v4.1.0):

in your functions.php add:

/**
 * Customize ordering by price
 */
add_filter('woocommerce_get_catalog_ordering_args', function ($args) {
    $orderby_value = isset($_GET['orderby']) ? wc_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby'));

    if ('price' == $orderby_value) {
        $args['orderby'] = 'meta_value_num';
        $args['order'] = 'ASC';
        $args['meta_key'] = '_price';
    }

    if ('price-desc' == $orderby_value) {
        $args['orderby'] = 'meta_value_num';
        $args['order'] = 'DESC';
        $args['meta_key'] = '_price';
    }

    return $args;
});

like @Pelmered mentioned it is important to use meta_value_num as the 'order_by' option so the ordering is done by number values and not string values. I changed the meta_key to '_price' though, because that is required in the WooCommerce version used and mentioned above.

Further reading:

WordPress Documentation WP_Query

WooCommerce Documentation Custom sorting options

Upvotes: 6

Abolfazl Sharifi
Abolfazl Sharifi

Reputation: 359

for anyone who may be faced with this problem

according to: https://woocommerce.wordpress.com/2019/04/01/performance-improvements-in-3-6/

if you imported your products with tools such as "WP All Import", you have to regenerate "Product lookup tables" in:

WooCommerce > Status > Tools > Product lookup tables

Upvotes: 18

PapaSoft
PapaSoft

Reputation: 53

You should update your Woocommerce plugin to the latest version. It was a bug in the plugin or you probably changed something in core functions.

Update helped me well with this and several other issues.

Upvotes: 0

Pelmered
Pelmered

Reputation: 2892

You need to use meta_value_num when you order by numeric meta data, otherwise it will compared as strings otherwise because the post meta values are stored as strings in the database.

$args = array(
    'meta_key' => 'price',
    'orderby' => 'meta_value_num',
    'order' => 'ASC'
);
$query = new WP_Query( $args );

Upvotes: 2

interlaw
interlaw

Reputation: 67

It seems that sorts out properly. See featured products, as they have priority.

Upvotes: 0

Related Questions