Skip to content

Instantly share code, notes, and snippets.

@bekarice
Last active May 13, 2022 15:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bekarice/0df2b2d54d6ac8076f84 to your computer and use it in GitHub Desktop.
Save bekarice/0df2b2d54d6ac8076f84 to your computer and use it in GitHub Desktop.
Add WooCommerce sorting by meta fields
<?php
/**
* Adds WooCommerce catalog sorting options using postmeta, such as custom fields
* Tutorial: http://www.skyverge.com/blog/sort-woocommerce-products-custom-fields/
**/
function skyverge_add_postmeta_ordering_args( $sort_args ) {
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
switch( $orderby_value ) {
// Name your sortby key whatever you'd like; must correspond to the $sortby in the next function
case 'location':
$sort_args['orderby'] = 'meta_value';
// Sort by meta_value because we're using alphabetic sorting
$sort_args['order'] = 'asc';
$sort_args['meta_key'] = 'location';
// use the meta key you've set for your custom field, i.e., something like "location" or "_wholesale_price"
break;
case 'points_awarded':
$sort_args['orderby'] = 'meta_value_num';
// We use meta_value_num here because points are a number and we want to sort in numerical order
$sort_args['order'] = 'desc';
$sort_args['meta_key'] = 'points';
break;
}
return $sort_args;
}
add_filter( 'woocommerce_get_catalog_ordering_args', 'skyverge_add_postmeta_ordering_args' );
// Add these new sorting arguments to the sortby options on the frontend
function skyverge_add_new_postmeta_orderby( $sortby ) {
// Adjust the text as desired
$sortby['location'] = __( 'Sort by location', 'woocommerce' );
$sortby['points_awarded'] = __( 'Sort by points for purchase', 'woocommerce' );
return $sortby;
}
add_filter( 'woocommerce_default_catalog_orderby_options', 'skyverge_add_new_postmeta_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'skyverge_add_new_postmeta_orderby' );
@schmentle
Copy link

This worked in the new release of Woocommerce. Just changed the sorting in Dashboard -> Appearance -> Customize -> Woocommerce.

Thanks a lot.

@orloxgr
Copy link

orloxgr commented Mar 3, 2021

How can we use the above code with points_awarded but also include after the points_awarded products those that do not have points_awarded metakey?
Thank you.

@ptrkx-wy
Copy link

Unfortunately this snippet does not work. Is there any way to adapt it to a current Woocommerce version?

@missvanna
Copy link

How to add product popularity sort by last 30days?

@mrkaluzny
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment