Sortable Custom Field Column in Admin Lists
Adds a column showing the value of a custom field, such as a price, event date or SKU, to an admin list and lets you sort the list by it.
Opens WPIDE on
Code
// Custom field to show.
$wpide_meta_column_key = 'price';
$wpide_meta_column_label = 'Price';
$wpide_meta_column_type = 'post';
// true to sort as numbers, false to sort as text.
$wpide_meta_column_numeric = true;
add_filter( "manage_{$wpide_meta_column_type}_posts_columns", function ( $columns ) use ( $wpide_meta_column_label ) {
$columns['wpide_meta_column'] = $wpide_meta_column_label;
return $columns;
} );
add_action( "manage_{$wpide_meta_column_type}_posts_custom_column", function ( $column, $post_id ) use ( $wpide_meta_column_key ) {
if ( 'wpide_meta_column' === $column ) {
$value = get_post_meta( $post_id, $wpide_meta_column_key, true );
echo '' === $value ? '–' : esc_html( is_scalar( $value ) ? $value : wp_json_encode( $value ) );
}
}, 10, 2 );
add_filter( "manage_edit-{$wpide_meta_column_type}_sortable_columns", function ( $columns ) use ( $wpide_meta_column_key ) {
$columns['wpide_meta_column'] = $wpide_meta_column_key;
return $columns;
} );
add_action( 'pre_get_posts', function ( $query ) use ( $wpide_meta_column_key, $wpide_meta_column_numeric ) {
if ( ! is_admin() || ! $query->is_main_query() || $query->get( 'orderby' ) !== $wpide_meta_column_key ) {
return;
}
$query->set( 'meta_key', $wpide_meta_column_key );
$query->set( 'orderby', $wpide_meta_column_numeric ? 'meta_value_num' : 'meta_value' );
} );
Notes
Set the key, label, post type and whether values are numbers; sorting a large list by a meta value is slower than by date.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.