[WooCommerce] Sort by Custom Attributes

Update

I created a plugin for this plus many other features. Click here to view it.

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, I 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.

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 I 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.

The code is as follows


/************* 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 ***************************/

This should be placed in the functions.php file of your theme.

 

Liked it? share it.FacebookLinkedInTwitterGoogle+Email

21 thoughts on “[WooCommerce] Sort by Custom Attributes

  1. Daniel

    Hey, thanks for this I found it really useful!
    However, I can’t get it to update the meta data using a product import plugin. I would have thought save_post would have been hooked and everything would be sweet. Any ideas why it won’t save the attributes to the posts meta data on import?
    Similarly, it doesn’t update if I do a bulk edit either… The metadata only gets written if I edit and save each product individually :\ I think I’m missing something…

    Reply
    1. Galal Aly Post author

      Well, imported data and quick edits require more work and handling extra cases. save_post however is the correct action hook. But you need another approach :)

      Reply
  2. Mike

    Hi Galal,

    Thank you for your solution, it works perfectly! What I’d really like to be able to do is set the Custom Attribute as the ‘Default Product Sorting’ option in the Woocommerce backend.

    Do you have any idea how to do that?

    Reply
    1. Mike

      Actually, don’t worry about it, I’ve decided to use the the built in Woocommerce menu order as it suits my site better and I can upload the data via the CSV suite using ‘menu_order’ as a custom field. Thanks anyway!

      Reply
        1. sfsdfsfsfs@mail.com

          Great idea! I’ve just tried to install your plugin and when I click the button “Process products” nothing seems to happen (button is grayed out already for about 1 hour now), I do have to notice that I have over 2,000 products in my store and I don’t actually know what the process behind the button action is, but maybe it’s just timing out because of the volume it needs to check? Isn’t there a possibility to change some code manually in the plugin so my desired custom attributes to sort on become visible? Thanks!

          Reply
  3. Pingback: Woocommerce learning | My Blog

  4. Dana

    First, thanks so very much for this code.

    I added the code to my site and now I can see the option to sort the products by, but when I select it I am told “No products were found matching your selection.”.

    The only thing I changed was the name of the attribute to sort by.

    Any ideas???

    Reply
  5. ms.ntcb.edu.tw

    It is the best time to make some plans for the future and it is time to be happy.
    I have read this post and if I could I want to suggest you few interesting things or tips.
    Perhaps you could write next articles referring to this article.
    I want to read even more things about it!

    Reply
  6. turystyka praca magisterska

    Having read this I thought it was rather enlightening.
    I appreciate you spending some time and energy to
    put this informative article together. I once
    again find myself spending way too much time both
    reading and commenting. But so what, it was still worth it!

    Reply
  7. world cup soccer 2015

    There have been Romanian players in the worldwide championship for the
    3rd time in a row. In truth, the continent of Asia manufactured its first physical appearance with the Dutch East Indies (modern-day Indonesia).
    Also, Cuba despatched athletes to France, turning into
    the initial Caribbean country to do so in the historythe recreation.

    Exceptionally, the Cuban nationwide staff had a very
    good performance regardless of its inexperience.

    Overall, it positioned seventh, at the price of Romania and the
    host nation. Obtaining gained the gold at the I Central American and Caribbean Video games in 1930, the island’s crew only acquired bronze in the regional online games in the
    mid-thirties in El Salvador.

    Reply
  8. Pingback: sorting by name and sku number in woo commerce | Baljit Web Developer

  9. pisanie prac

    Yesterday, while I was at work, my cousin stole my iPad and
    tested to see if it can survive a twenty five foot drop, just so she can be a youtube
    sensation. My apple ipad is now destroyed and she has 83 views.
    I know this is entirely off topic but I had to share it with someone!

    Reply

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>