WooCommerce: Sort Products using meta key

WooCommerce is one always the best option for building an online store based on WordPress. There are heaps of advantages of using WooCommerce but one of the best thing is WooCommerce’s long list of hooks to customise the functionlity.

Today, we will learn about how to sort products listing using meta key.
By default WooCommerce comes with a couple of sorting options which include
Popularity
Average rating
Sort by most recent
Sort by price

You can find these default sort options in WordPress admin area.
– Ligin to your store
– Go to Appearance -> Customising
– Click Product Catalogue
– Click Default product sorting dropdown

But what if you want to sort your products based on some custom field? Don’t worry, we have really simple solution for this. Let’s proceed with a real-time example.

Let’s assume you have a store of online books. Now, you want to sort books by Publish date. The field in the backend named “Book Publish Date”

You can sort the WooCommerce shop page by the custom field book_publish_date by modifying the pre_get_posts query. Add the following code to your theme’s functions.php file:

Code to Sort WooCommerce Shop by Book Publish Date
php
Copy
Edit
function custom_sort_books_by_publish_date( $query ) {
if ( ! is_admin() && $query->is_main_query() && ( is_shop() || is_product_category() || is_product_tag() ) ) {
$query->set( ‘meta_key’, ‘book_publish_date’ );
$query->set( ‘orderby’, ‘meta_value’ );
$query->set( ‘order’, ‘DESC’ ); // Change to ‘ASC’ for oldest first
}
}
add_action( ‘pre_get_posts’, ‘custom_sort_books_by_publish_date’ );
Explanation:
meta_key: Specifies book_publish_date as the sorting field.
orderby: Uses meta_value to sort by custom field value.
order: DESC for newest books first; change to ASC for oldest first.
is_shop() || is_product_category() || is_product_tag(): Ensures sorting applies to the shop page, category pages, and tag pages.
Additional Considerations
Ensure book_publish_date is stored as a proper date format (YYYY-MM-DD) in post meta.
If the field is stored as a timestamp or number, change orderby to meta_value_num:
php
Copy
Edit
$query->set( ‘orderby’, ‘meta_value_num’ );
If sorting doesn’t work, check if the meta key exists for all products using:
php
Copy
Edit
global $wpdb;
$results = $wpdb->get_results( “SELECT * FROM $wpdb->postmeta WHERE meta_key = ‘book_publish_date’ LIMIT 10” );
print_r($results);
Would you like any refinements, such as adding sorting dropdown options for users?