You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Woocommerce排序问题:非特色新品前置,需调整至末尾

问题解决与代码调整

问题分析

  1. 特色排序与最新排序结果一致:WooCommerce原生不支持直接用featured作为orderby参数,当前代码的设置无效,导致实际仍按默认日期排序,因此和“最新添加”排序结果重合。
  2. 非特色新品排在首位:未指定非特色商品的次级排序规则,默认按商品添加日期降序排列,所以新品会排在非特色商品的最前面。

修改后的完整代码

//// WOOCOMMERCE SORTING //////

add_filter( 'woocommerce_catalog_orderby', 'fa_remove_default_sorting_options' );
 
function fa_remove_default_sorting_options( $options ){
    unset( $options[ 'popularity' ] );
    // 保留其他默认排序选项,可根据需要注释
    //unset( $options[ 'menu_order' ] );
    //unset( $options[ 'rating' ] );
    //unset( $options[ 'date' ] );
    //unset( $options[ 'price' ] );
    //unset( $options[ 'price-desc' ] );
 
    return $options;
}

// 添加特色排序选项
add_filter( 'woocommerce_catalog_orderby', 'add_featured_catalog_orderby' );
function add_featured_catalog_orderby( $orderby_options ) {
    $orderby_options['featured'] = __( "按特色商品优先排序", "woocommerce" );
    return $orderby_options;
}

// 设置默认排序为特色优先
add_filter( 'woocommerce_default_catalog_orderby', 'set_default_featured_orderby' );
function set_default_featured_orderby( $default_orderby ) {
    return 'featured';
}

// 处理特色排序的查询逻辑
add_action( 'woocommerce_product_query', 'custom_featured_product_query' );
function custom_featured_product_query( $q ) {
    if ( is_admin() ) return;

    $orderby = isset( $_GET['orderby'] ) ? $_GET['orderby'] : get_option( 'woocommerce_default_catalog_orderby' );

    if ( 'featured' === $orderby ) {
        // 优先显示特色商品,然后非特色商品按添加日期升序(新品在末尾)
        $q->set( 'meta_query', array(
            'relation' => 'OR',
            array(
                'key'     => '_featured',
                'value'   => 'yes',
                'compare' => '='
            ),
            array(
                'key'     => '_featured',
                'compare' => 'NOT EXISTS'
            )
        ) );
        // 设置排序规则:先按特色标记降序(yes在前),再按添加日期升序
        $q->set( 'orderby', array(
            'meta_value' => 'DESC',
            'date'       => 'ASC'
        ) );
        $q->set( 'meta_key', '_featured' );
    }
}

代码改动说明

  1. 修复特色排序无效问题:通过meta_query筛选特色商品(基于_featured元字段),明确设置排序规则,确保特色商品优先显示。
  2. 调整非特色商品排序:在特色排序规则中,次级排序设置为date ASC,非特色商品按添加日期从早到晚排列,最新添加的非特色商品会排在整个列表的末尾。
  3. 优化排序选项添加逻辑:直接在原排序选项数组中添加特色排序,避免数组拼接可能的冲突。

内容的提问来源于stack exchange,提问作者bilkyroot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 10:54:20