admin管理员组

文章数量:1193808

firstly, sorry for my english :(

I have a custom admin post column

add_filter('manage_posts_columns', 'my_columns');
function my_columns($columns) {
    $columns['views'] = 'Views';
    return $columns;
}

add_action('manage_posts_custom_column',  'my_show_columns');
function my_show_columns($name) {
    global $post;
    switch ($name) {
        case 'views':
            $views = get_post_meta($post->ID, 'views', true);
            echo $views;
    }
}

How can I change the code that I can click ob the headline in the admin I can change the order from DESC or to ASC?

The Wordpress column "Title" has a little arrow right side but my custom VIEWS not :( Do you can help me?

br garfield853

firstly, sorry for my english :(

I have a custom admin post column

add_filter('manage_posts_columns', 'my_columns');
function my_columns($columns) {
    $columns['views'] = 'Views';
    return $columns;
}

add_action('manage_posts_custom_column',  'my_show_columns');
function my_show_columns($name) {
    global $post;
    switch ($name) {
        case 'views':
            $views = get_post_meta($post->ID, 'views', true);
            echo $views;
    }
}

How can I change the code that I can click ob the headline in the admin I can change the order from DESC or to ASC?

The Wordpress column "Title" has a little arrow right side but my custom VIEWS not :( Do you can help me?

br garfield853

Share Improve this question edited Sep 26, 2022 at 14:06 Nabha Cosley 6883 silver badges11 bronze badges asked Sep 24, 2022 at 13:49 matstilmatstil 1 1
  • smashingmagazine.com/2017/12/… – cameronjonesweb Commented Sep 24, 2022 at 15:07
Add a comment  | 

1 Answer 1

Reset to default 1

Thanks to @cameronjonesweb's link, here's the code you might use:

add_filter( 'manage_edit-post_sortable_columns', 'my_add_sortable_custom_column');
function my_add_sortable_custom_column( $columns ) {
  $columns['views'] = 'views';
  return $columns;
}

add_action( 'pre_get_posts', 'my_sort_custom_column' );
function my_sort_custom_column( $query ) {
  if( ! is_admin() || ! $query->is_main_query() ) {
    return;
  }

  if ( 'views' === $query->get( 'orderby') ) {
    $query->set( 'orderby', 'meta_value' );
    $query->set( 'meta_key', 'views' );
    $query->set( 'meta_type', 'numeric' ); 
  }
}

The first one registers the column as sortable, while the second changes the query when WordPress wants to sort by that column.

本文标签: Custom Admin Post Column change order