johnbillion / extended-cpts

A library which provides extended functionality to WordPress custom post types and taxonomies.
GNU General Public License v2.0
979 stars 96 forks source link

set order_by parameter for admin columns to meta_value_num #65

Open ajuliano opened 7 years ago

ajuliano commented 7 years ago

We are using this for all out projects. It's awesome. However, we would love the feature to sort set the order_by parameter for admin columns to meta_value_num.

I saw that there is a // @TODO meta_value_num on line 466. But I couldn't solve the problem to make a pull request. We would have to add another parameter to $sortables to make it work right? I couldn't figure out how to do that in the right manner.

chood531 commented 7 years ago

@ajuliano - I solved this by doing the following in the extended-cpts.php plugin file.

if ( isset( $orderby['meta_key'] ) ) {

    $return['meta_key'] = $orderby['meta_key'];
    $return['orderby'] = 'meta_value';

    if(isset($orderby['meta_value_num']) && $orderby['meta_value_num']) {
        $return['orderby'] = 'meta_value_num';  
    }

} else if ( isset( $orderby['post_field'] ) ) {
    $field = str_replace( 'post_', '', $orderby['post_field'] );
    $return['orderby'] = $field;
}

Next, when using the register_extended_post_type function to register a post type, in the admin_cols array item which needs meta_value_num, add a new item to the array:

'admin_cols' => [
    'percent_complete' => [
        'title' => 'Percent Complete',
        'meta_key' => '_percent_complete',
        'meta_value_num' => true
    ]
]