• 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
     * http://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)
  • Thanks so much for posting this. I would have spent a day on this myself.

    Now if I could just figure out how to sort on a custom field by default.

    //’orderby’ => ‘meta_value_num’, // does not work
    ‘orderby’ => ‘meta_value’

    'orderby' => 'meta_value_num' does work as it is supposed to, since the postmeta table stores all data as text the default sort is going to be a string sort instead of a numeric sort. If you are ordering by a numeric field meta_value_num will give the correct results and meta_value will not.

    $sort_values = array(35,1,3,1,8,13,2,5,21);

    after ‘meta_value_num’: $sort_values = array(1,1,2,3,5,8,13,21,35);
    after ‘meta_value’: $sort_values = array(1,1,13,2,21,3,35,5,8);

    Thread Starter tzeldin88

    (@tzeldin88)

    @totels – Thanks for clarifying this for others reading this thread.

    My php-comment “//does not work” was not meant to imply that meta_value_num is broken, but just that it is the wrong approach to the sorting i was trying to do, which was on a Date field, like “2011-04-23” (yyyy-mm-dd).

    I initally tried using meta_value_num, which i had found in code from Scribu (http://scribu.net/wordpress/custom-sortable-columns.html), which did not do what i wanted, then i finally found a comment from TS (http://scribu.net/wordpress/custom-sortable-columns.html#comment-4732) that used meta_value instead, which solved my problem.

    I’m working on a similar thing but haven’t managed to get it working with the code above (I must be missing something).

    I too have a date column which I want to sort but I want to sort by the actual data value rather than whats displayed. This is beacsue I have made the dates ‘pretty’ (eg Thursday 1st June….) so at the moment its sorting by the the pretty version of the date.

    Hope you can help.

    Ok, this works for me except that posts without any data in the start_datetime meta field don’t show. Any ideas?

    // Enable sortable dates column
    function will_events_sortable_columns( $columns ) {
    $columns['dates_datetime'] = 'start_datetime';
    
    return $columns;
    }
    add_filter( 'manage_edit-events_sortable_columns', 'will_events_sortable_columns' );
    
    // Sort by...
    function will_event_datetime_column_orderby( $vars ) {
    if ( isset( $vars['orderby'] ) && 'start_datetime' == $vars['orderby'] ) {
    
    $vars = array_merge( $vars, array(
    'meta_key' => 'start_datetime',
    'orderby' => 'meta_value'
    ));
    }
    
    return $vars;
    }
    add_filter( 'request', 'will_event_datetime_column_orderby' );

    Great work @tzeldin88

    Am using this in my latest project.

    If you use the Make Headers Sortable chunk to target “default” columns (author, categories, tags etc.) then WP does the rest for you, even on Custom Post Types

    mixdmatt, could you show me the exact code you used for that (default headers)? I’m not sure what part of the “make headers sortable chunk” you mean.

    Thank you.

    Just a note to say thank you. This saved me hours of time.

    Thanks for posting this, it’s saved me a lot of time on a client site.

    One tip that someone might find useful… I had a few column headings containing spaces eg. ‘Car Colour’ – wouldn’t sort. ‘CarColour’ sorts fine.

    @clompers

    To set a custom column to sort by default, try adjusting @tzeldin88’s last code snippet by adding “!isset( $vars[‘orderby’] )” to it, like this:

    /*
     * ADMIN COLUMN - SORTING - ORDERBY
     * http://scribu.net/wordpress/custom-sortable-columns.html#comment-4732
     */
    add_filter( 'request', 'city_column_orderby' );
    function city_column_orderby( $vars ) {
    	if ( !isset( $vars['orderby'] ) || ( 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;
    }

    codepress-admin-columns

    This plugin gives you a nice interface to control all the column headers. It also supports sortings for post(types).

    http://wordpress.org/extend/plugins/codepress-admin-columns/

    I have recently released it, so any feedback is welcome!

    codepress, your plugin is extremely handy. Great work! 5 stars (just rated it.)

    The only thing not working for me is attachments: the count doesn’t show up, and the attachments themselves don’t show up. FYI I am also using the Attachments plugin: http://wordpress.org/extend/plugins/attachments/

    Hi mt33,

    I had a look at the attachment plugin, and the reason it doesn’t show the attachments is because the data (images) from this plugin is not saved as an actual attachment. It is saved in a hidden custom field (also know as metadata).

    The Codepress Admin Column plugin can show images from custom fields, but not when they are hidden. I will have a closer look at it, because maybe I can make an option which will let you choose hidden fields aswell. That would solve your problem.

    And thanks for the rating, really helps a lot!

    Tobias

Viewing 13 replies - 1 through 13 (of 13 total)
  • The topic ‘Admin Column Sorting’ is closed to new replies.