Skip to content

Instantly share code, notes, and snippets.

@ethanhinson
Created November 11, 2013 20:00
Show Gist options
  • Save ethanhinson/7419385 to your computer and use it in GitHub Desktop.
Save ethanhinson/7419385 to your computer and use it in GitHub Desktop.
Add a custom sortable column to a WordPress custom post type admin list.
<?php
/**
*
* Custom sortable columns on property admin list
*
*/
function property_id_column_register( $columns ) {
// Insert property ID in between date/title
$last = array_pop($columns);
$columns['prop_id'] = 'Property ID';
$columns[strtolower($last)] = $last;
return $columns;
}
add_filter( 'manage_property_posts_columns', 'property_id_column_register' );
// Display the column content
function property_id_column_display( $column_name, $post_id ) {
if ( 'prop_id' != $column_name )
return;
$prop_id = get_post_meta($post_id, 'wpcf-property-id', true);
if ( !$prop_id )
$prop_id = '<em>No ID entered!</em>';
echo $prop_id;
}
add_action( 'manage_property_posts_custom_column', 'property_id_column_display', 10, 2 );
// Register the column as sortable
function property_id_column_register_sortable( $columns ) {
$columns['prop_id'] = 'prop_id';
return $columns;
}
add_filter( 'manage_edit-property_sortable_columns', 'property_id_column_register_sortable' );
// Make our sorting work
function property_id_column_orderby( $vars ) {
if ( isset( $vars['orderby'] ) && 'prop_id' == $vars['orderby'] ) {
$vars = array_merge( $vars, array(
'meta_key' => 'wpcf-property-id',
'orderby' => 'meta_value'
) );
}
return $vars;
}
add_filter( 'request', 'property_id_column_orderby' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment