Is there a way to get products in the order of the IDs in the shortcode parameter:

e.g [products ids="53,68,1"]

Display block with 3 product, where 53 on first place, 68 on second...?

Now I get products sorted by sku, name etc. Depending on order-by parameter, but I need specific order.


3 Answers 3

     function woo_products( $atts ) {
         global $post;
         $product_Out = '';
                $atts = shortcode_atts(
           'product_ids' => '',// your product id goes here
         ), $atts, 'bartag' );
         $pro_ids = explode(",", $atts['product_ids']);
         foreach ($pro_ids as $key => $values) {
            $product_obj = $product = wc_get_product( $values );
            //call your html and data in $product out variable
            $product_Out .= '<div class="product_name">'.$values.'</div>';
         return $product_Out;
     add_shortcode( 'woo_products', 'woo_products' );
     //use this shortcode [woo_products product_ids="9,86"]

I know, it's an older post, but I recently came up with the same problem, with the help of this topic pre_get_posts with WooCommerce Shortcode Query I finally found a solution. Just add this filter to your functions:

add_filter( 'woocommerce_shortcode_products_query', 'woocommerce_shortcode_products_orderby' );
function woocommerce_shortcode_products_orderby( $args ) {
    $standard_array = array('menu_order','title','date','rand','id');

    if( isset( $args['orderby'] ) && !in_array( $args['orderby'], $standard_array ) ) {
    $args['orderby']  = 'post__in'; 

    return $args;

B4rT's answer has the right idea, but there's no need to code an additional filter for it. the [products] shortcode essentially uses WP_Query, so if you set the order to post__in, it will naturally order posts by the order in which they're passed:

[products ids="53,68,1" orderby="post__in"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.