Snippet: Numeric sortable column for custom post type in admin panel

Many developer used Property, Car, Product and several others as a custom post type which, by default, sorted by publishing date (very odd). This fairly simple snippet details how one can add a sortable numeric column (for example a pricing column) in listing view of custom post type. It is quite useful as custom post types are getting popular day by day.

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>