Display WooCommerce products in custom order

The [products] shortcode is a powerful tool for displaying a list of products on a WooCommerce store. It allows you to specify the number of products to show, the number of columns to display them in, and even which specific products to show by ID. However, there is a limitation in that the products are not displayed in the order specified by the ids attribute. Instead, the default behavior is to sort the products alphabetically by name.

If you want to change the order in which the products are displayed to match the order specified in the ids attribute, there is a solution. The woocommerce_shortcode_products_query_results hook runs after the products have been queried from the database, but before they are displayed on the page. By hooking into this hook and modifying the order of the results, it is possible to display the products in the desired order.

To achieve this, you can use the following code snippet:

//Products shortcode custom order by id
add_filter('woocommerce_shortcode_products_query_results', 'bytflow_custom_products_shortcode_order', 10, 2);
function bytflow_custom_products_shortcode_order($results, $shortcode_products){
	$attributes = $shortcode_products->get_attributes();
    $order_by_arg = get_query_var('orderby');
	// Check if there are any ids specified and that user didn't change the order
	if (empty($order_by_arg) && ! empty( $attributes['ids'] ) ) {
		$ids = explode( ',', $attributes['ids'] );
        $ordered_results = array();
        foreach ($ids as $id){
            if(in_array($id, $results->ids)){
	            $ordered_results[] = $id;
		$results->ids = $ordered_results;
    return $results;

This code checks for the presence of the ids attribute in the shortcode and, if it exists, rearranges the products in the $results->ids array to match the order specified in the attribute. This ensures that the products are displayed in the desired order when the shortcode is used. If the orderby parameter is in the url, the code won’t reorder results.

In summary, if you want to display a list of products using the [products] shortcode in a specific order, you can use the woocommerce_shortcode_products_query_results hook and the code snippet provided above to achieve this. This will allow you to fully customize the display of your products on your WooCommerce store.

Leave a Comment