Custom sortable columns ordered by meta-value?

I have no idea why my sortable function does not sort my “events” my a custom post-meta. I have a custom-post-type named wr_event… I have my custom columns set up and my post-meta is shown in the columns, just like I want. The “Event-Date” handle even is already a sortable link! Only thing if I click on the sort-link for the event date the list doesn’t update. The function is fired as I see the page reloading however it doesn’t sort anyhing.

Even though the url toggles between those two states if I click the sort-link …

Read More

http://url/wp-admin/edit.php?post_type=wr_event&orderby=event_date&order=desc

http://url/wp-admin/edit.php?post_type=wr_event&orderby=event_date&order=asc

However the list always looks the same!

Here is my entire code for the custom columns:

add_filter("manage_edit-wr_event_columns", "wr_event_edit_columns");

function wr_event_edit_columns($columns) {
    $columns = array(
        "cb" => "<input type="checkbox" />",
        "title" => "Event",
        "event_date" => "Event Date",
        "type" => "Type",
    );

    return $columns;
}

add_action("manage_posts_custom_column",  "event_custom_columns");

function event_custom_columns($column) {
    global $post;

    switch ($column) {
        case "event_date":
        $custom = get_post_custom();
        echo $custom['_wr_event_date'][0];
        break;
        case "type":
        echo get_the_term_list($post->ID, 'event_type', '', ', ','');
        break;
    }
}

add_filter("manage_edit-wr_event_sortable_columns", "wr_event_sortable_columns");   

function wr_event_sortable_columns( $columns ) {
    $columns['event_date'] = 'event_date';
    return $columns;
}

add_filter("request", "event_column_orderby");

function event_column_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'event_date' == $vars['event_date'] ) {
        $vars = array_merge( $vars,
            array(
                'meta_key'  => '_wr_event_date',
                'orderby'   => 'meta_value_num',
                'order'     => 'asc'
            )
        );
    }

    return $vars;
}

Related posts

Leave a Reply

1 comment

  1. It’s because you are checking 'event_date' == $vars['event_date'] not 'event_date' == $vars['orderby].

    But don’t use the request filter. Instead:

    add_action( 'pre_get_posts', 'event_column_orderby' );  
    function event_column_orderby( $query ) {  
        if( ! is_admin() )  
            return;  
    
        $orderby = $query->get( 'orderby');  
    
        if( 'event_date' == $orderby ) {  
            $query->set('meta_key','_wr_event_date');  
            $query->set('orderby','meta_value_num');  
        }  
    } 
    

    … and don’t manually set the order as you won’t then see the difference when toggling between ASC/DESC.