Woocommerce产品按自定义字段排序

时间:2018-12-03 19:37:37

标签: php sorting woocommerce product custom-fields

我的产品具有不同的自定义帖子类型:持续时间和最高海拔。

我为过滤器创建了一个函数,可以在产品页面上使用它,但是没有自定义字段的产品要先于具有自定义字段的产品。示例:我有3个产品:Product1,Product2和Product3,产品1&2的持续时间分别设置为10和20。当我选择过滤它们duration_asc时,我得到Product3(无字段),Product1,Product2。

这是我的代码:

add_filter( 'woocommerce_get_catalog_ordering_args', 'add_custom_postmeta_ordering_args' );
function add_custom_postmeta_ordering_args( $sort_args ) {
    $orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );

    switch( $orderby_value ) 
    {
        case 'duration_desc':
            $sort_args['orderby'] = 'meta_value_num';
            $sort_args['order'] = 'desc';
            $sort_args['meta_key'] = 'duration';
            break;

        case 'duration_asc':
            $sort_args['orderby'] = 'meta_value_num';
            $sort_args['order'] = 'asc';
            $sort_args['meta_key'] = 'duration';
            break;

        case 'maxheight_desc':
            $sort_args['orderby'] = 'meta_value_num';
            $sort_args['order'] = 'asc';
            $sort_args['meta_key'] = 'maxheight';
            break;

        case 'maxheight_asc':
            $sort_args['orderby'] = 'meta_value_num';
            $sort_args['order'] = 'asc';
            $sort_args['meta_key'] = 'maxheight';
            break;
    }
    return $sort_args;
}

add_filter( 'woocommerce_default_catalog_orderby_options', 'add_custom_new_postmeta_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'add_custom_new_postmeta_orderby' );
function add_custom_new_postmeta_orderby( $sortby ) {
    // Adjust the text as desired
    $sortby['duration_desc'] = __( 'Duration - highest first', 'strings' );
    $sortby['duration_asc'] = __( 'Duration - lowest first', 'strings' );
    $sortby['maxheight_desc'] = __( 'From max altitude', 'strings' );
    $sortby['maxheight_asc'] = __( 'From min altitude', 'strings' );

    return $sortby;
}

有什么想法可以实现这一目标吗?

0 个答案:

没有答案