简体   繁体   中英

How order by date column in WordPress admin panel?

I'm using Events Manager plugin for WordPress. I add a column with Event's start time and i would like to order by this time in admin panel. Column are sortable, is displaying timestamp, but it's not ordering correct, it's random.

Here is my code:

add_filter('manage_edit-event_columns', 'my_columns');
function my_columns($columns) {
    $columns['datanowa'] = 'Nowa data wydarzenia';
    return $columns;
}
add_action('manage_posts_custom_column',  'my_show_columns');
function my_show_columns($name) {
    global $post;
    switch ($name) {
        case 'datanowa':
            $nowadata = new DateTime();
            $EM_Event = em_get_event($post, 'post_id');
            $nowadataunix = $EM_Event->start;
            $nowadata->setTimestamp($nowadataunix);
            //echo $nowadata->format('j F Y');
            echo $nowadataunix;
            break;
    }
}
add_filter( 'manage_edit-event_sortable_columns', 'my_sortable_banana_column');
function my_sortable_banana_column( $columns ) {
$columns['datanowa'] = 'datanowa';
return $columns;
}

在此输入图像描述

Since WordPress doesn't know how to handle 'orderby=datanow', you'll have to change that, by altering the query variables. Instead of using the Event Manager methods to get the startdate, try to find out which meta field is used and query it directly into your query, something like this

function sort_datanowa_column( $vars ) {
    if ( isset( $vars['orderby'] ) && 'datanowa' == $vars['orderby'] ) {
        $vars = array_merge( $vars, array(
            'meta_key' => 'start_date', // Find correct meta field key
            'orderby' => 'meta_value_num'
        ) );
    } 
    return $vars;
}
add_filter( 'request', 'sort_datanowa_column' );

You could also have a look at http://www.admincolumns.com which allows you to add columns based on custom fields and make them sortable filterable and editable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM