Using WordPress ‘filter_default_metadata()’ PHP function

The filter_default_metadata() WordPress PHP function filters into default_{$object_type}_metadata and adds a default value.

Usage

Let’s suppose we want to add a default value for a metadata key ‘author_bio’ for a ‘post’ object. Here’s how you might do it:

add_filter( 'default_post_metadata', 'my_default_metadata', 10, 5 );

function my_default_metadata( $value, $object_id, $meta_key, $single, $meta_type ) {
    if ( 'author_bio' == $meta_key ) {
        $value = 'Default Author Bio';
    }
    return $value;
}

In this example, if ‘author_bio’ doesn’t already have a value, it will be set to ‘Default Author Bio’.

Parameters

  • $value (mixed) – The current value passed to filter.
  • $object_id (int) – The ID of the object the metadata is for.
  • $meta_key (string) – The metadata key.
  • $single (bool) – If true, return only the first value of the specified $meta_key. This parameter has no effect if $meta_key is not specified.
  • $meta_type (string) – The type of object the metadata is for. Accepts ‘post’, ‘comment’, ‘term’, ‘user’, or any other object type with an associated meta table.

More information

See WordPress Developer Resources: filter_default_metadata()

Examples

Default Comment Metadata

Set a default metadata value for ‘comment_rating’ of a ‘comment’ object.

add_filter( 'default_comment_metadata', 'my_default_comment_metadata', 10, 5 );

function my_default_comment_metadata( $value, $object_id, $meta_key, $single, $meta_type ) {
    if ( 'comment_rating' == $meta_key ) {
        $value = 5; // Set default rating to 5
    }
    return $value;
}

Default User Metadata

Adding a default metadata value for ‘user_status’ of a ‘user’ object.

add_filter( 'default_user_metadata', 'my_default_user_metadata', 10, 5 );

function my_default_user_metadata( $value, $object_id, $meta_key, $single, $meta_type ) {
    if ( 'user_status' == $meta_key ) {
        $value = 'active'; // Set default status to 'active'
    }
    return $value;
}

Single Post Metadata

Returning only the first value of the specified $meta_key for a ‘post’ object.

add_filter( 'default_post_metadata', 'my_default_post_metadata', 10, 5 );

function my_default_post_metadata( $value, $object_id, $meta_key, $single, $meta_type ) {
    if ( 'post_title' == $meta_key && $single ) {
        $value = 'Default Post Title'; 
    }
    return $value;
}

Term Metadata

Adding a default metadata value for ‘term_description’ of a ‘term’ object.

add_filter( 'default_term_metadata', 'my_default_term_metadata', 10, 5 );

function my_default_term_metadata( $value, $object_id, $meta_key, $single, $meta_type ) {
    if ( 'term_description' == $meta_key ) {
        $value = 'Default Term Description'; 
    }
    return $value;
}