Web Development Woocommerce Wordpress

Show featured products on top on woocommerce shop page

add_filter('posts_orderby', 'products_orderby_featured',10,2);
function products_orderby_featured($order_by, $query){
  global  $wpdb ;
  if( ($query->get('post_type')=='product') && (!is_admin()) ){
    $orderby_value = ( isset( $_GET['orderby'] ) ? wc_clean( (string) $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) ) );
    $orderby_value_array = explode( '-', $orderby_value );
    $orderby = esc_attr( $orderby_value_array[0] );
    $order = ( !empty($orderby_value_array[1]) ? $orderby_value_array[1] : 'ASC' );
    $feture_product_id = get_featured_products();    
    if ( is_array( $feture_product_id ) && !empty($feture_product_id) ) {
      if ( empty($order_by) ) {
        $order_by = "FIELD(" . $wpdb->posts . ".ID,'" . implode( "','", $feture_product_id ) . "') DESC ";
      } else {
        $order_by = "FIELD(" . $wpdb->posts . ".ID,'" . implode( "','", $feture_product_id ) . "') DESC, " . $order_by;
      }
    }  
  }
  return $order_by;
}

Add this code to active theme functions.php, it will work with woocommerce 3.

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image