Sorry! Internet Explorer is not supported on this site. Please view on Chrome, Firefox, or Edge.

Having fun at Zao is one of our values. We’ve put limited animated flourishes throughout our site to communicate our love of levity. We also recognize that onscreen movement is not fun or possible for everyone. We've turned off all our animations for you per your browser's request to limit motion. That said, we don't want you to miss out on the party.

Here's a funny joke to enjoy!

Where does the General keep his armies?

In his sleevies!

How To: Sort Variations in WP eCommerce

One of the neat things about WP e-Commerce is the vast array of filters and actions available.  I had a client ask me this week for a custom sorting routine for their variations on the front-end.

For anyone unaware – variations are essentially different attributes of a product.  If the product were a T-shirt, for example, variations would be Size (with Small, Medium and Large) as options or Color (Black, Red, Green), etc.

The code below would allow you to sort each group (and options within that group) according to a custom sorting algorithm.  A pretty handy little code snippet!

// This compares the names of the variation term object.
function zao_compare_variations( $a, $b ) {
    return strcmp( $a->name, $b->name );
}

// This pops off the first option (which is always --Please Select--)
// Then it sorts the remaining actual options with our custom sort function
// Finally, it pops the first option back on and returns the $variations array.
function zao_resort_variations( $variations, $groups, $product_id ) {

    foreach ( $variations as $group => $variants ) {

        $first = array_shift( $variants );

        usort( $variants, 'zao_compare_variations' );

        array_unshift( $variants, $first );

        $variations[ $group ] = $variants;
    }

    return $variations;
}

add_filter( 'wpsc_all_associated_variations', 'zao_resort_variations', 10, 3 );

Leave a comment

Your email address will not be published.