WooCommerce products shortcode order by sku list

Is there a way to modify the WooCommerce Products shortcode to order by a list of product sku’s?

A search engine send a Post to the page with a list of sku’s. The page should display the Products in the same order the http post is.

Read More

Example php and mysql select (the code like this worked in my old shop system where I can use SQL syntax):

$_POST['skus'] = "51,57,34,12,111";
$skus = $_POST['skus'];

select * from products where sku in ('$skus') order by FIELD(sku,'$skus);

How can I do an “orderby” like the example with products shortcode from woocommerce or is there a better way to do that with woocommerce?

Thanks for every answer.

Related posts

1 comment

  1. With the help from Gavin and the code from https://wordpress.stackexchange.com/a/67830/43362
    I found this solution:

        function wpse67823_orderby_post_in($orderby, $query){
    
         //Remove it so it doesn't effect future queries
         remove_filter(current_filter(), __FUNCTION__);
    
         $post__in = $_POST['skus'];
    
         $post__in = str_replace(',','','',$post__in);
    
         return "FIELD(CAST(mt2.meta_value AS CHAR), '$post__in' )";
         } 
    
        //Add filter and perform query
        add_filter('posts_orderby','wpse67823_orderby_post_in',10,2);
    
        echo do_shortcode('[products skus="'.$skus.'" orderby="sku"]');
    
        remove_filter('posts_orderby','wpse67823_orderby_post_in',10,2);
    

Comments are closed.