Using WordPress ‘postmeta_form_keys’ PHP filter

postmeta_form_keys is a WordPress PHP filter that modifies the meta key dropdown values in the Custom Fields meta box. By returning a non-null value, you can avoid an expensive query against the postmeta table.

Usage

add_filter('postmeta_form_keys', 'my_custom_postmeta_keys', 10, 2);
function my_custom_postmeta_keys($keys, $post) {
    // your custom code here
    return $keys;
}

Parameters

  • $keys (array|null): Pre-defined meta keys to be used instead of a postmeta query. Default is null.
  • $post (WP_Post): The current post object.

More information

See WordPress Developer Resources: postmeta_form_keys

Examples

Adding Custom Meta Keys to Dropdown

This example adds custom meta keys to the dropdown list in the Custom Fields meta box.

add_filter('postmeta_form_keys', 'add_custom_meta_keys', 10, 2);
function add_custom_meta_keys($keys, $post) {
    $custom_keys = array('custom_key_1', 'custom_key_2', 'custom_key_3');
    return array_merge($keys, $custom_keys);
}

Restricting Meta Keys Based on User Role

This example restricts the available meta keys in the dropdown based on the user’s role.

add_filter('postmeta_form_keys', 'restrict_meta_keys_by_role', 10, 2);
function restrict_meta_keys_by_role($keys, $post) {
    $user = wp_get_current_user();
    if (in_array('editor', $user->roles)) {
        return array('editor_key_1', 'editor_key_2');
    } elseif (in_array('author', $user->roles)) {
        return array('author_key_1', 'author_key_2');
    }
    return $keys;
}

Adding Post-specific Meta Keys

This example adds post-specific meta keys to the dropdown based on the post type.

add_filter('postmeta_form_keys', 'add_post_specific_meta_keys', 10, 2);
function add_post_specific_meta_keys($keys, $post) {
    if ($post->post_type == 'custom_post_type') {
        $custom_keys = array('cpt_key_1', 'cpt_key_2');
        return array_merge($keys, $custom_keys);
    }
    return $keys;
}

Removing Default Meta Keys

This example removes the default meta keys from the dropdown list.

add_filter('postmeta_form_keys', 'remove_default_meta_keys', 10, 2);
function remove_default_meta_keys($keys, $post) {
    return array();
}

Using Post ID to Filter Meta Keys

This example filters the meta keys in the dropdown based on the post ID.

add_filter('postmeta_form_keys', 'filter_meta_keys_by_post_id', 10, 2);
function filter_meta_keys_by_post_id($keys, $post) {
    if ($post->ID == 123) {
        $custom_keys = array('post_123_key_1', 'post_123_key_2');
        return array_merge($keys, $custom_keys);
    }
    return $keys;
}