skip to Main Content

I’m using woocommerce shortcode to display custom products loop, e.g. [products limit="-1" paginate="true" orderby="menu_order" columns="5" ids="85,11,1083,256,37,12,517,68,2577,104"]. But there’s a problem – they are displaying sorted by title, but I need them to be sorted in that exact order they are in shortcode. I found no such option in shortcodes docs. Is there a way to achieve it with shortcode?

2

Answers


  1. Chosen as BEST ANSWER

    Solution found: orderby = "post__in"

    Source: Woocommerce Product Short Code Order by Order of IDs


  2. 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.

    //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. Source

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search