Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.