Make custom column sortable

Make sure to change MY_POST_TYPE, MY_CUSTOM_COLUMN and MY_META_KEY to the actual values.

First, add your custom column. Unset the date and set it again to keep it in the last column. You can skip this step.

<?php
function my_manage_MY_POST_TYPE_columns( $columns )
{
    // save date to the variable
    $date = $columns['date'];
    // unset the 'date' column
    unset( $columns['date'] ); 
    // unset any column when necessary
    // unset( $columns['comments'] );

    // add your column as new array element and give it table header text
    $columns['MY_CUSTOM_COLUMN'] = __('Custom Column Header Text');

    $columns['date'] = $date; // set the 'date' column again, after the custom column

    return $columns;
}
?>

Second, make your column sortable using manage_edit-{$post_type}_sortable_columns filter (not documented yet).

<?php
function my_set_sortable_columns( $columns )
{
    $columns['MY_CUSTOM_COLUMN'] = 'MY_CUSTOM_COLUMN';
    return $columns;
}
?>

Third, populate column cells.

<?php
function my_populate_custom_columns( $column, $post_id )
{
    switch ( $column ) {
        case 'MY_CUSTOM_COLUMN':
            echo get_post_meta($post_id, 'MY_META_KEY', true);
            break;
        case 'MAYBE_ANOTHER_CUSTOM_COLUMN':
            // additional code
            break;
    }
}
?>

Now you are ready to actually sort that column.

Note: if you don’t check meta_query for empty (non-existent) values, your column will show only the posts having (non-empty) meta value until it will be sorted by another by default or another column

<?php
function my_sort_custom_column_query( $query )
{
    $orderby = $query->get( 'orderby' );

    if ( 'MY_CUSTOM_COLUMN' == $orderby ) {

        $meta_query = array(
            'relation' => 'OR',
            array(
                'key' => 'MY_META_KEY',
                'compare' => 'NOT EXISTS', // see note above
            ),
            array(
                'key' => 'MY_META_KEY',
            ),
        );

        $query->set( 'meta_query', $meta_query );
        $query->set( 'orderby', 'meta_value' );
    }
}
?>

And now let’s apply filters and actions. Check if you are not on the front-end, on the right page and the right post type is chosen:

<?php
global $pagenow;

if ( is_admin() && 'edit.php' == $pagenow && 'MY_POST_TYPE' == $_GET['post_type'] ) {

    // manage colunms
    add_filter( 'manage_MY_POST_TYPE_posts_columns', 'my_manage_MY_POST_TYPE_columns' );

    // make columns sortable
    add_filter( 'manage_edit-MY_POST_TYPE_sortable_columns', 'my_set_sortable_columns' );

    // populate column cells
    add_action( 'manage_MY_POST_TYPE_posts_custom_column', 'my_populate_custom_columns', 10, 2 );

    // set query to sort
    add_action( 'pre_get_posts', 'my_sort_custom_column_query' );
}

?>

Leave a Comment