postmeta_form_keys
Allows you to change the set of meta fields in the Custom Fields meta box dropdown.

If the filter returns a value other than null, such as an empty array or an array of strings, the default query that collects all post meta field names for the dropdown is canceled and its result is replaced with the filter's return value.
Before output, the key array is passed through the natcasesort() sorting function.
Usage
add_filter( 'postmeta_form_keys', 'wp_kama_postmeta_form_keys_filter', 10, 2 );
/**
* Function for `postmeta_form_keys` filter-hook.
*
* @param array|null $keys Pre-defined meta keys to be used in place of a postmeta query.
* @param WP_Post $post The current post object.
*
* @return array|null
*/
function wp_kama_postmeta_form_keys_filter( $keys, $post ){
// filter...
return $keys;
}
- $keys(array/null)
- Meta field names (keys from the
meta_keycolumn of thewp_postmetatable) to display in the dropdown.
Default: null - $post(WP_Post)
- Current post object.
Examples
#1 Explicitly specify the keys displayed in the dropdown
Specify a preset list of meta field keys for every custom post type:
add_filter( 'postmeta_form_keys', 'filter_postmeta_form_keys' );
function filter_postmeta_form_keys(){
return [ 'key_field_1', 'key_field_2' ];
}
#2 Combine keys for display in the dropdown
Account for the filter being called in different parts of the code, with each callback adding meta field keys to the shared pool. Keys may be duplicated, so duplicates must also be removed.
add_filter( 'postmeta_form_keys', 'filter_1_postmeta_form_keys' );
add_filter( 'postmeta_form_keys', 'filter_2_postmeta_form_keys' );
function filter_1_postmeta_form_keys( $keys ) {
$my_keys = [ 'key_field_1', 'key_field_2' ];
$keys = array_merge( (array) $keys, $my_keys );
return array_unique( $keys );
}
function filter_2_postmeta_form_keys( $keys ) {
$my_keys = [ 'key_field_2', 'key_field_3' ];
$keys = array_merge( (array) $keys, $my_keys );
return array_unique( $keys );
}
The result:
#3 Specify keys only for cpt=product
add_filter( 'postmeta_form_keys', 'filter_postmeta_form_keys', 10, 2 );
function filter_postmeta_form_keys( $keys, $post ) {
if ( 'product' === get_post_status( $post ) ) {
$keys = [ 'stock', 'sale' ];
}
return $keys;
}
#4 Prevent retrieval of every post meta field key
add_filter( 'postmeta_form_keys', '__return_empty_array' );
Changelog
| Since 4.4.0 | Introduced. |
Where the hook is called
postmeta_form_keys
wp-admin/includes/template.php 709
$keys = apply_filters( 'postmeta_form_keys', null, $post );

