How to Add and Display Custom Meta Data in WordPress Admin Posts List?

The code adds a “Custom Meta” field to the WordPress admin posts list, allowing you to display, edit, and save custom metadata directly from the Quick Edit screen. A new column titled “Custom Meta” shows the custom field value for each post dynamically.

// Add a custom column for the `posts` post type
add_filter('manage_posts_columns', 'ts_add_custom_meta_column', 10, 2);
function ts_add_custom_meta_column($posts_columns, $post_type) {
    $posts_columns['custom_meta'] = 'Custom Meta';
    return $posts_columns;
}

// Display the custom meta value in the custom column
add_action('manage_posts_custom_column', 'ts_show_custom_meta_column', 10, 2);
function ts_show_custom_meta_column($column_name, $post_id) {
    if ('custom_meta' === $column_name) {
        // Retrieve and display the custom meta value
        $custom_meta_value = get_post_meta($post_id, '_custom_meta_key', true);
        echo esc_html($custom_meta_value);
    }
}

// Add the custom meta box to the quick edit screen
add_action('quick_edit_custom_box', 'ts_add_custom_meta_quick_edit_box', 10, 2);
function ts_add_custom_meta_quick_edit_box($column_name, $post_type) {
    if ('custom_meta' === $column_name) {
        $custom_meta_value = '';
        // Get the custom meta value if editing an existing post
        if (isset($_GET['post'])) {
            $custom_meta_value = get_post_meta($_GET['post'], '_custom_meta_key', true);
        }
        ?>
        <div class="inline-edit-group">
            <label class="alignleft">
                <span class="title">Custom Meta</span>
                <input type="text" name="custom_meta" value="<?php echo esc_attr($custom_meta_value); ?>" />
            </label>
        </div>
        <?php
    }
}

// Save the custom meta value when quick editing
add_action('save_post', 'ts_save_custom_meta_value');
function ts_save_custom_meta_value($post_id) {
    // Check if our custom meta field is set
    if (isset($_POST['custom_meta'])) {
        // Sanitize and save the custom meta value
        update_post_meta($post_id, '_custom_meta_key', sanitize_text_field($_POST['custom_meta']));
    }
}