Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

categories - Woocommerce - Display Featured Products at top of Category Page

I want to have a section at the top of each product category page that shows three featured products at random from that category. Beneath this would be the regular archive loop.

What's the best way to achieve this, without using a plugin?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Below code can help you:

    add_filter('posts_orderby', 'show_featured_products_orderby',10,2);
function show_featured_products_orderby($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 = wc_get_featured_product_ids();
    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 themes function.php file


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...