Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ataylorme/4100806 to your computer and use it in GitHub Desktop.
Save ataylorme/4100806 to your computer and use it in GitHub Desktop.
Add sortable custom field columns to WordPress backend
// Register the column
function METAKEYHERE_column_register( $columns ) {
$columns['METAKEYHERE'] = __( 'COLUMNLABEL', 'POSTTYPE' );
return $columns;
}
add_filter( 'manage_edit-POSTTYPE_columns', 'METAKEYHERE_column_register' );
// Display the column content
function METAKEYHERE_column_display( $column_name, $post_id ) {
if ( 'METAKEYHERE' != $column_name )
return;
$METAKEYHERE = get_post_meta($post_id, 'METAKEYHERE', true);
if ( !$METAKEYHERE ){
$METAKEYHERE = 'No phone';
}
else {
$METAKEYHERE;
}
echo $METAKEYHERE;
}
add_action( 'manage_posts_custom_column', 'METAKEYHERE_column_display', 10, 2 );
add_action( 'manage_pages_custom_column', 'METAKEYHERE_column_display', 10, 2 );
// Register the column as sortable
function METAKEYHERE_column_register_sortable( $columns ) {
$columns['METAKEYHERE'] = 'METAKEYHERE';
return $columns;
}
add_filter( 'manage_edit-POSTTYPE_sortable_columns', 'METAKEYHERE_column_register_sortable' );
function METAKEYHERE_column_orderby( $vars ) {
if ( isset( $vars['orderby'] ) && 'METAKEYHERE' == $vars['orderby'] ) {
$vars = array_merge( $vars, array(
'meta_key' => 'METAKEYHERE',
'orderby' => 'meta_value_num'
) );
}
return $vars;
}
add_filter( 'request', 'METAKEYHERE_column_orderby' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment