Woocommerce - 在类别页面顶部显示特色产品

问题描述 投票:1回答:1

我想在每个产品类别页面的顶部有一个部分,从该类别中随机显示三个特色产品。在此之下将是常规归档循环。

在不使用插件的情况下,实现这一目标的最佳方法是什么?

woocommerce categories product archive featured
1个回答
2
投票

下面的代码可以帮助您:

    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;
}

将此代码添加到活动主题function.php文件中

© www.soinside.com 2019 - 2024. All rights reserved.