0

I have custom post type named Cars.

By default, it is sorted by post publishing date, which is very unusual.

WordPress should have provided option to sort columns containing numeric values. Alas, it's not available, and I am looking for solution for the same. Help is appreciated.

1 Answer 1

2

Try

// 1. Register the column
add_filter( 'manage_edit-post_columns', 'price_column_register' );
function price_column_register( $columns ) {
    $columns['price'] = __( 'Price', 'theme' );

    return $columns;
}

// 2. Display the column content
add_action( 'manage_posts_custom_column', 'price_column_display', 10, 2 );
function price_column_display( $column_name, $post_id ) {
    if ( 'price' != $column_name )
        return;

    $price = get_post_meta($post_id, 'price', true);
    if ( !$price )
        $price = '<em>' . __( 'undefined', 'theme' ) . '</em>';

    echo $price;
}

// 3. Register the column as sortable
add_filter( 'manage_edit-post_sortable_columns', 'price_column_register_sortable' );
function price_column_register_sortable( $columns ) {
    $columns['price'] = 'price';

    return $columns;
}

// 4. here is the sorting brain
add_filter( 'request', 'price_column_orderby' );
function price_column_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'price' == $vars['orderby'] ) {
        $vars = array_merge( $vars, array(
            'meta_key' => 'price',
            'orderby' => 'meta_value_num',
            'order' => 'asc'

        ) );
    }

    return $vars;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.