Reputation:
I need to sort products for a specific category in WooCommerce by sky. Tried different combinations but non of work. Like I tried the bellow
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'orderby' => 'sku',
'order' => 'asc',
'posts_per_page' => $atts['per_page'],
'meta_query' => $meta_query,
'tax_query' => array(
'relation' => 'OR',
array(
'taxonomy' => 'product_cat',
'terms' => array_map('sanitize_title', explode(',', $atts['category'])),
'field' => 'slug',
'operator' => $atts['operator']
),
array(
'taxonomy' => 'product_tag',
'terms' => array_map('sanitize_title', explode(',', $atts['tags'])),
'field' => 'slug',
'operator' => $atts['operator']
)
)
);
$products = new WP_Query($args);
Where $attrs[] data are coming from shortcode parameters. But it does not sort product by sku ?
A help will be greatly appreciated.
Upvotes: 0
Views: 2901
Reputation: 553
The product sku (_sku) is saved as meta value, thus you cant simply say "order by sku", you should order by meta value, and set the meta keyto _sku. If they do not have a sku set the products will not be displayed.
Example:
args = array(
'post_type' => 'product',
'meta_key' => '_sku',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => '_sku',
'compare' => 'EXISTS',
),
),
);
If your sku is numeric you should use "meta_value_num" if the sku's are strings then use "meta_value" instead.
You can read more about it here -> https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
Upvotes: 2