WooCommerce属性筛选:如何按数值排序属性值?
WooCommerce Gutenberg 属性筛选数值排序问题解决方法
问题背景
- 使用WooCommerce默认属性筛选功能,未安装第三方筛选插件
- 后台属性已按
name_num规则正确排序,但前端Gutenberg属性筛选块中的属性值仍按字母排序(例如8排在25之后),修改后台排序规则无效 - 需保留当前Gutenberg样式,不切换旧小工具编辑器、不使用其他筛选插件,仅实现属性值按数值排序
解决方法
将以下PHP代码添加到主题的functions.php文件或自定义代码插件中,即可针对指定属性实现数值排序:
add_filter( 'woocommerce_block_attribute_filter_terms', 'custom_sort_attribute_terms_numerically', 10, 3 ); function custom_sort_attribute_terms_numerically( $terms, $attribute, $query_vars ) { // 替换为需要数值排序的属性ID,示例为13 $target_attribute_id = 13; if ( $attribute->get_id() === $target_attribute_id ) { // 按属性名称的数值大小排序 usort( $terms, function( $a, $b ) { return (int) $a->name - (int) $b->name; } ); } return $terms; }
扩展说明
- 若多个属性需要数值排序,可将判断条件改为数组匹配:
if ( in_array( $attribute->get_id(), [13, 15, 20] ) )(替换为你的属性ID列表) - 该代码仅作用于WooCommerce的Gutenberg属性筛选块,不会影响后台或其他前端区域的属性排序逻辑
内容的提问来源于stack exchange,提问作者libertarian
相关产品推荐
相关产品推荐

