I figured out how to sort products displayed via shortcode by SKU or Custom Fields.
For SKU, this would go into functions.php:
add_filter('woocommerce_shortcode_products_query', 'add_shortcode_orderby_options', 10, 2);
function add_shortcode_orderby_options ($args, $atts) {
if ($atts['orderby'] == "sku") {
$args['orderby'] = 'meta_value';
$args['meta_key'] = '_sku';
}
return $args;
return $atts;
}
That allows a shortcode like this to be used:
[product_category category="my-category" orderby="sku"]
It also works with other shortcodes that display a list of products like [featured_products]
and
[products]
.
I think other meta keys can be used, as well. There is a list of possible meta keys here. They can also be found by scanning files found in plugins/woocommerce/includes/admin/meta-boxes
For Custom Fields, it would be something like this:
add_filter('woocommerce_shortcode_products_query', 'add_shortcode_orderby_options', 10, 2);
function add_shortcode_orderby_options ($args, $atts) {
if ($atts['orderby'] == "my-custom-sorting-option") {
$args['orderby'] = 'meta_value';
$args['meta_key'] = 'my_custom_field_name';
}
return $args;
return $atts;
}
Then your shortcode would be something like:
[product_category category="my-category" orderby="my-custom-sorting-option"]
You’d create a Custom Field by going to Admin Panel > Products > Edit Product. Under Add New Custom Field, click Enter New. The name would be my_custom_field_name and the value would reflect the desired sorting position for that product (i.e. “1”). Click the Add Custom Field button, then Update the product. For your next product, you can choose my_custom_field_name from the dropdown menu, assign it a value (i.e. “2”), and click Add Custom Field then Update.
Note: I’m using the same function name in both of these examples. If you want to allow more than one sorting option, use one function and add a separate if statement for each sorting option.