Admin Column Sorting
-
Admin Column Sorting for a custom field in a Custom Post Type.
I spent most of the day on this.. but couldn’t find all of it together in one place. Finally got all the pieces together so it was working for me. Sharing in case it helps anyone.
This is for a Custom Post Type called “concerts” (already registered). The custom field getting a new column is “city”. Here are the pieces, all in functions.php:
– Column/Header
– Content
– Sorting: Headers
– Sorting: OrderBy (*this was hard to find, thanks Scribu -and- TS!)/* * ADMIN COLUMN - HEADERS */ add_filter('manage_edit-concerts_columns', 'add_new_concerts_columns'); function add_new_concerts_columns($concerts_columns) { $new_columns['cb'] = '<input type="checkbox" />'; $new_columns['title'] = _x('Club', 'column name'); $new_columns['city'] = __('City'); return $new_columns; } /* * ADMIN COLUMN - CONTENT */ add_action('manage_concerts_posts_custom_column', 'manage_concerts_columns', 10, 2); function manage_concerts_columns($column_name, $id) { global $post; switch ($column_name) { case 'city': echo get_post_meta( $post->ID , 'city' , true ); break; default: break; } // end switch } /* * ADMIN COLUMN - SORTING - MAKE HEADERS SORTABLE * https://gist.github.com/906872 */ add_filter("manage_edit-concerts_sortable_columns", 'concerts_sort'); function concerts_sort($columns) { $custom = array( 'concertdate' => 'concertdate', 'city' => 'city' ); return wp_parse_args($custom, $columns); /* or this way $columns['concertdate'] = 'concertdate'; $columns['city'] = 'city'; return $columns; */ } /* * ADMIN COLUMN - SORTING - ORDERBY * https://scribu.net/wordpress/custom-sortable-columns.html#comment-4732 */ add_filter( 'request', 'city_column_orderby' ); function city_column_orderby( $vars ) { if ( isset( $vars['orderby'] ) && 'city' == $vars['orderby'] ) { $vars = array_merge( $vars, array( 'meta_key' => 'city', //'orderby' => 'meta_value_num', // does not work 'orderby' => 'meta_value' //'order' => 'asc' // don't use this; blocks toggle UI ) ); } return $vars; }
Viewing 13 replies - 1 through 13 (of 13 total)
Viewing 13 replies - 1 through 13 (of 13 total)
- The topic ‘Admin Column Sorting’ is closed to new replies.