# 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.

- Type: PHP
- Runs: Admin only
- Category: [Admin](https://wpide.com/library/category/admin/)
- Tags: admin-columns, custom-fields, sorting
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/admin-custom-field-column/

## Code

```php
// 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 ? '&ndash;' : 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Sortable Custom Field Column in Admin Lists" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
