How to sort and order WooCommerce products by Custom Attributes

To add extra sorting options to your WooCommerce pages using products’ meta data you can use the following

http://docs.woothemes.com/document/custom-sorting-options-ascdesc/

However, we wanted to add some sorting options that use the WooCommerce’s custom attributes. According to this thread, the product attributes are saved in a serialized format in the database and therefore it’s not feasible to do it directly using WordPress orderby attribute.

Our Approach

To use the provided WooCommerce filters the attributes should be saved as meta data.

When a post that has some custom attributes set is updated, the submitted data ($_REQUEST) contains the following:


'attribute_names' =>
 array (
 0 => 'pa_pub-year',
 1 => 'pa_pub-author',
...
 ),
 'attribute_position' =>
 array (
 0 => '1',
 1 => '1',
......
'attribute_is_taxonomy' =>
 array (
 0 => '1',
......
 ),
 'attribute_values' =>
 array (
 0 => '1990',
 1 => '',
 2 => '',
......
 ),

The approach we followed is to get the submitted attributes and save them as post meta data. Afterwards, the code provided by WooCommerce to sort using attributes, with a tiny modification, worked successfully.

Sample Code

Place the following code in your theme’s functions.php


/************* Add sorting by attributes **************/

/**
 *	Defines the criteria for sorting with options defined in the method below
 */
add_filter('woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args');

function custom_woocommerce_get_catalog_ordering_args( $args ) {
	global $wp_query;
        // Changed the $_SESSION to $_GET
	if (isset($_GET['orderby'])) {
		switch ($_GET['orderby']) :
			case 'pa_pub-year' :
				$args['order'] = 'ASC';
				$args['meta_key'] = 'pa_pub-year';
				$args['orderby'] = 'meta_value_num';
			break;
		endswitch;
	}
	return $args;
}

/**
 *	Adds the sorting options to dropdown list .. The logic/criteria is in the method above
 */
add_filter('woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby');

function custom_woocommerce_catalog_orderby( $sortby ) {
	$sortby['pa_pub-year'] = 'Sort by Year: Older to Newer';
	return $sortby;
}

/**
 *	Save custom attributes as post's meta data as well so that we can use in sorting and searching
 */
add_action( 'save_post', 'save_woocommerce_attr_to_meta' );
function save_woocommerce_attr_to_meta( $post_id ) {
        // Get the attribute_names .. For each element get the index and the name of the attribute
        // Then use the index to get the corresponding submitted value from the attribute_values array.
	foreach( $_REQUEST['attribute_names'] as $index => $value ) {
		update_post_meta( $post_id, $value, $_REQUEST['attribute_values'][$index] );
	}
}
/************ End of Sorting ***************************/

11 thoughts to “How to sort and order WooCommerce products by Custom Attributes”

  1. I like the precious details anyone look after your posts. I am going to save your web site and check just as before right here routinely. I am just relatively positive I am knowledgeable a great deal of new goods listed here! All the best . for the next!

  2. I have been exploring for a bit for any high-quality articles or blog posts in this
    kind of area . Exploring in Yahoo I at last stumbled upon this web site.
    Reading this info So i am glad to exhibit that I’ve a very just right uncanny feeling I found out just what I needed.
    I so much definitely will make sure to do not
    forget this website and provides it a glance on a relentless basis.

  3. I’m really inspired with your writing skills and also with the format in your blog.
    Is this a paid theme or did you modify it your self?
    Anyway stay up the nice high quality writing, it is rare to
    peer a great weblog like this one today..

  4. My brother recommended I may like this website. He was entirely
    right. This publish actually made my day. You can not believe simply how a lot time I had spent for this information!
    Thanks!

  5. Have you ever thought about including a little bit more than just your articles?
    I mean, what you say is valuable and everything. But think about if you
    added some great pictures or videos to give your posts more, “pop”!
    Your content is excellent but with images and videos, this blog could definitely
    be one of the best in its field. Very good blog!

Leave a Reply

Your email address will not be published. Required fields are marked *