首页 > 解决方案 > 按产品尺寸(长度、宽度和高度)排序的 Wordpress (Woocommerce)

问题描述

我正在尝试按长度和宽度订购我的产品,首先按长度排序,如果两个产品具有相同的值,它将按宽度排序(依此类推)。如果我能先让它工作,我想增加高度。

到目前为止,我遇到的问题是它按长度和仅按长度订购产品(加上一个错误,即使长度不正确,即产品订单是 2.1、2 和 2.5)。

这是我从查询中得到的:

function woocommerce_catalog_orderby( $args ) {
    $args['meta_query'] = array(
        'relation' => 'AND',
        'length_clause' => array(
            'key'     => '_length',
            'type' => 'DECIMAL',
            'orderby' => 'meta_value_num',
        ),
        'width_clause' => array(
            'key'     => '_width',
            'type' => 'DECIMAL',
            'orderby' => 'meta_value_num',
        ),
    );

    $args['orderby'] = array(
        'length_clause' => 'ASC',
        'width_clause' => 'ASC',
    );

    return $args;
}
add_filter('woocommerce_get_catalog_ordering_args', 'woocommerce_catalog_orderby');

我确信我错过了一些我目前看不到的明显东西。任何帮助深表感谢!

标签: wordpresswoocommerce

解决方案


在您的情况下,您必须在为 woocommerce 添加过滤器时添加优先级。这是按元值排序的工作代码:

/**

'''
 function wh_save_product_custom_meta($post_id, $post, $update) {
        $post_type = get_post_type($post_id);
        // If this isn't a 'product' post, don't update it.
        if ($post_type != 'product')
            return;
    
        if (!empty($_POST['attribute_names']) && !empty($_POST['attribute_values'])) {
            $attribute_names = $_POST['attribute_names'];
            $attribute_values = $_POST['attribute_values'];
            foreach ($attribute_names as $key => $attribute_name) {
                switch ($attribute_name) {
                    //for color (string)
                    case 'pa_color':
                        //it may have multiple color (eg. black, brown, maroon, white) but we'll take only the first color.
                        if (!empty($attribute_values[$key][0])) {
                            update_post_meta($post_id, 'pa_color', $attribute_values[$key][0]);
                        }
                        break;
                    //for lenght (int)
                    case 'pa_length':
                        if (!empty($attribute_values[$key][0])) {
                            update_post_meta($post_id, 'pa_length', $attribute_values[$key][0]);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }
    
    add_action( 'save_post', 'wh_save_product_custom_meta', 10, 3);
'''   


推荐阅读