Search
Close this search box.

wordpress产品按照自定义字段排序代码

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

发表评论

Optimized by WPJAM Basic