Created
November 17, 2012 22:30
-
-
Save ataylorme/4100806 to your computer and use it in GitHub Desktop.
Add sortable custom field columns to WordPress backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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