pre_get_posts with WooCommerce Shortcode Query

You could use the WooCommerce filter woocommerce_shortcode_products_query to change/manipulate the query arguments.

This example comes from the shortcode documentation.

When using the Products shortcode, you can choose to order products by the pre-defined values above. You can also sort products by custom meta fields using the code below (in this example we order product by price):

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['meta_key'] = $args['orderby'];
    $args['orderby']  = 'meta_value_num'; 
  }

 return $args;
}

Leave a Comment