skip to Main Content

I would like to order the product display by the ids that are entered in [products ids=””] short code. I need it to order by the order you enter it. So… [products ids=”1,2,3″] [products ids=”3,1,2″] [products ids=”2,3,1″] … all list differently.

I found this piece of code that I think is close but doesn’t quite work. I’m not real familiar with this method so I am not sure what is wrong.

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;

I read up on post__in but not sure how it gets the ID list I entered. Is there another/better way to grab that id list and use it for the order?

Any ideas on how to get this thing to work?

2

Answers


  1. Just add order by in your shortcode like –

    [products ids="1,2,3" orderby="post__in"]
    [products ids="3,1,2" orderby="post__in"]
    [products ids="2,3,1" orderby="post__in"]
    
    Login or Signup to reply.
  2. Update from 2020.

    The products shortcode can’t handle this orderby

    So you can create your own foreach loop:

    foreach ($products_to_show_array as $_product_id) {
        setup_postdata( $GLOBALS['post'] );
    
        // Render product template.
        wc_get_template_part( 'content', 'product' );
    }
    wp_reset_postdata();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search