Using WordPress ‘get_metadata_default()’ PHP function

The get_metadata_default() WordPress PHP function retrieves the default metadata value for the specified meta key and object.

Usage

get_metadata_default( $meta_type, $object_id, $meta_key, $single )

Example:

$default_meta_value = get_metadata_default( 'post', 42, 'custom_key', true );

Parameters

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

More information

See WordPress Developer Resources: get_metadata_default

Examples

Retrieve default post metadata

In this example, we retrieve the default metadata value for a post with ID 42 and meta key ‘custom_key’.

$default_meta_value = get_metadata_default( 'post', 42, 'custom_key', true );
echo $default_meta_value;

Retrieve default user metadata

In this example, we retrieve the default metadata value for a user with ID 3 and meta key ‘user_bio’.

$default_meta_value = get_metadata_default( 'user', 3, 'user_bio', true );
echo $default_meta_value;

Retrieve default term metadata

In this example, we retrieve the default metadata value for a term with ID 7 and meta key ‘term_description’.

$default_meta_value = get_metadata_default( 'term', 7, 'term_description', true );
echo $default_meta_value;

Retrieve all default metadata values for a post

In this example, we retrieve all the default metadata values for a post with ID 42 and no specific meta key.

$all_default_meta_values = get_metadata_default( 'post', 42, '', false );
print_r( $all_default_meta_values );

Retrieve default comment metadata

In this example, we retrieve the default metadata value for a comment with ID 10 and meta key ‘comment_rating’.

$default_meta_value = get_metadata_default( 'comment', 10, 'comment_rating', true );
echo $default_meta_value;