You are on page 1of 23

Blog

By Beka Rice on December 22, 2014in category Tutorials, WooCommerce Tutorialstags development, frontend, WooCommerce
and 5 comments.

Sort WooCommerce Products by


Custom Fields or Post Meta
Weve got a plugin that will allow you to add WooCommerce product sorting options (not to mention
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

one that will remove core sorting options as desired), but you may need a more customized solution
for sorting your products.
In this case, you may want to sort WooCommerce products by your custom elds or by other post
meta values. Lets go over how we can add sorting options for custom elds that weve set for our
WooCommerce products. First, well go over what your custom elds should look like.

Add Custom Fields to WooCommerce Products


You can quickly add custom elds to all WooCommerce products by importing them with your
custom elds set as post meta. The WooCommerce Product CSV Import suite extension is great for
this, and will allow you to both export and import products. This will enable you to set post meta for
your products in bulk as needed export products, add this info, and re-import them to merge your
changes.
You can also add custom elds directly from the Edit Product screen:

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

This will allow you to add both text-based and number-based values for your post meta information.
Once this information has been added to products, youll be able to use it to sort them.

Sort WooCommerce Products by Custom Field


WooThemes has a bit of helpful information on how to sort WooCommerce products, but it doesnt
address the information well need to sort on: meta values. We can sort by meta values that are both
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

words and numbers, so well do an example of each in this sample snippet.


You can add as many new sorting options as youd like, but Im going to add two: Sort by location
(word-based) and Sort by points earned (number-based). This could be handy if you, for example, use
WooCommerce Points and Rewards for a loyalty program, but some products offer double or triple
points and youd like customers to know.
Now on to the code! If youre not sure how to add this, check out our tutorial on adding custom code
to your site. Im going to add it via the Code Snippets plugin.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

/**
* 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'] ) ? woocommerce_clean( $_GET['orderby'] ) : apply_filters( 'woo


switch( $orderby_value ) {

open in browser PRO version

// Name your sortby key whatever you'd like; must correspond to the $sortby in the next funct
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"
break;

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

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 nume
$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
' );

wc-sort-by-postmeta.phphosted with

by GitHub

view raw

Okay, so what is this doing? The rst part creates the sorting arguments. It tells WooCommerce what
to use to sort the products when these sorting options are used. You can add extra cases if youd like
to create more than 2 new sorting options.
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Notice in the rst one that Ive sorted by meta_value as I want to sort alphabetically, but in the
second example Ive used meta_value_num because I want to sort numerically. I can also
determine whether I should sort in ascending (asc) or descending (desc) order. Set these as desired.
For alphabetical sorting, I actually want to sort ascending, as A is a regarded as the starting value,
and Z is regarded as an ending (higher) value. For numerical sorting, Im going to sort descending
because I want the highest points shown rst.
As the last note on the rst function, I then tell WooCommerce which meta key should be used. This
will be the key for your custom eld, which will be something like location, points,
_wholesale_price , _stock, or others (if youre curious about the leading underscore, check this
out or this).
The second function here will just add my new sorting option to the frontend of my site, as well as
add it as a default option in the admin if Id like to use it for the default. You can edit this text as
desired, but Id keep it short since it will be in your dropdown on the shop pages.

What it looks like


Okay, so ready to see what it will look like when you sort WooCommerce products in your shop? First,
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

these options will be added to the sorting dropdown:

When I select one, the corresponding sorting arguments that weve added will be used. Ive added
the post meta to this screenshot so you can see it in action. Heres my alphabetical sorting by
location:

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

And heres my numerical sorting by points earned for purchasing:

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Pretty beautiful, huh?

A Potential Hiccup
You may notice that my examples above only include products that have these custom elds set. If
these custom elds are not available, they wont be included in the sorting options.
I like to keep it this way for stuff like location, as I may not want to show a bunch of products that
dont have a location assigned at all. However, for my points sorting, this wont do. I want to add
the rest of my products after this. You can do so by setting the points custom eld for the rest of
your products, but leaving it blank.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

I just did this with two products, and now theyre shown with this sorting:

This is why I recommend using the Product CSV import, as you can set all of these elds blank as
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

desired. If you try to do this within the Edit Product screen, just be aware youll run into a minor
speedbump. The product screen requires a value be set for a custom eld:

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

To work around this, just add your elds with some arbitrary value set:

You can then delete it the value to keep the custom eld blank and update your product.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Not as easy as importing, but it does the job. Now go and sort on all the meta elds you heart
desires
.
Found this useful? Please share it!
Twitter 7

Google

ManageWP

Facebook

Pocket

Email

About Beka Rice


Beka manages content for SkyVerge, including sales copy and documentation. She
also handles the boring administrative tasks, and likes to write so she has an excuse to spend
more time jamming out to anything from The Clash to Ke$ha.
View all of Bekas posts
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

5 Comments
John

Reply

7 months ago

Hi Beka,
How do you show the custom eld data below the product images?

Beka Rice

7 months ago

Reply

Hey John, great question Ill pencil in a tutorial on adding info to the
shop loop to explain what I did
.

Beka Rice

6 months ago

Reply

Hey John, this was just posted to show how to add data to the shop page:
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

https://www.skyverge.com/blog/add-information-to-woocommerce-shoppage/

Florian Ludwig

1 month ago

Reply

Hello everybody!
You wrote about the little hiccup: You may notice that my examples above only
include products that have these custom elds set.
I just solved this problem in my shop with the following code, where the check also
includes the posts without the speci c custom value set maybe you can add this to
your post:
add_filter( 'woocommerce_get_catalog_ordering_args',

'points_awarded_ordering_args');
function points_awarded_ordering_args($args) {
global $wpdb;
$orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) :
apply_filters( 'woocommerce_default_catalog_orderby', get_option(
'woocommerce_default_catalog_orderby' ) );
if ( 'points_awarded' == $orderby_value ) {
// Sorting handled later through a hook
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

add_filter( 'posts_clauses', 'order_by_points_awarded_post_clauses' );


}
return $args;
}
function order_by_points_awarded_post_clauses( $args ) {
global $wpdb;
$args['join'] .= "
LEFT JOIN wpshop_postmeta AS points ON (wpshop_posts.ID =
points.post_id AND favourite.meta_key = 'points_awarded')
";
$args['orderby'] = "favourite.meta_value DESC, $wpdb->posts.post_date DESC";
return $args;
}

Beka Rice

1 month ago

Reply

Thanks for this Florian

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Submit a Comment
Create an account with social login if you want us to remember you, or just complete the elds
below to comment without an account. Powered by WooCommerce Social Login.

Log in with Twitter

Log in with Google

Name *

Log in with Facebook

Email *

Website

Comment

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Submit Comment

Notify me of follow-up comments by email.


Notify me of new posts by email.

Join the Email List


open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Get news on product updates, releases, coupons, & WooCommerce tips!


P.S. No spam ever. Promise.
Email Address *
where to send awesome stuff
First Name
John
(Optional)

Submit

Search Site
Enter your query here...

Search Plugins
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Search for:
Search Products
Search

Plugin Categories
Free Extensions (8)
WooCommerce Extensions (65)
Integrations (11)
Orders & Reporting (10)
Payment Gateways (24)
Supports Refunds (2)
Product & Checkout Changes (11)
Shipping (3)
Shop management (11)
Supports Subscriptions (14)
WordPress.org Plugins (5)

Blog Categories
open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

Ask SkyVerge (33)


News (39)
Product Updates / Releases (48)
Tips (34)
Tutorials (83)
WooCommerce Tutorials (55)
WordPress Tutorials (18)

We Recommend

Check out the products and services


we love and recommend.

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

From the Blog

Join the Email


List!

WooCommerce
Memberships version 1.1
Released

350 WooCommerce Core


Contributions
Get news on product
65 WooCommerce
updates, releases,
extensions
coupons, &
5 WordPress.org Plugins
WooCommerce tips!
8 free WooCommerce
P.S. No spam ever.
extensions
Promise.
267,693 WordPress.org
Plugin Downloads
Email Address *
85 WooCommerce Articles
81 Blog Tutorials
where to send awesome stuff169 Total Blog Posts

Developers: Stop Using


sslverify = false
WordPress has you
covered
Add Text to the
WooCommerce Review
Form
WooCommerce
Memberships is here!

SkyVerge Stats

Search Site
Enter your query here...

More Info
My Account
We're Hiring!
We Recommend
Contact Us
Get Support

First Name
John
(Optional)

Submit

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com

2015 SkyVerge All Rights Reserved


Trademark| Privacy Policy| Terms of Service

open in browser PRO version

Are you a developer? Try out the HTML to PDF API

pdfcrowd.com