Using WordPress ‘get_{$meta_type}_metadata_by_mid’ PHP filter

The get_{$meta_type}_metadata_by_mid WordPress PHP filter allows you to short-circuit the return value when fetching a meta field by meta ID for various meta object types such as post, comment, term, user, etc.

Usage

add_filter( 'get_post_metadata_by_mid', 'your_custom_function', 10, 2 );

function your_custom_function( $value, $meta_id ) {
    // Your custom code here
    return $value;
}

Parameters

  • $value (stdClass|null): The value to return.
  • $meta_id (int): Meta ID.

More information

See WordPress Developer Resources: get_{$meta_type}_metadata_by_mid

Examples

Change post meta value by meta ID

Modify a specific post meta value based on its meta ID.

add_filter( 'get_post_metadata_by_mid', 'change_post_meta_by_mid', 10, 2 );

function change_post_meta_by_mid( $value, $meta_id ) {
    if ( $meta_id == 123 ) {
        $value = 'New Value';
    }
    return $value;
}

Block access to a specific user meta

Prevent access to a specific user meta value by its meta ID.

add_filter( 'get_user_metadata_by_mid', 'block_user_meta_by_mid', 10, 2 );

function block_user_meta_by_mid( $value, $meta_id ) {
    if ( $meta_id == 456 ) {
        $value = null;
    }
    return $value;
}

Add prefix to term meta value

Add a prefix to a term meta value by its meta ID.

add_filter( 'get_term_metadata_by_mid', 'add_prefix_to_term_meta_by_mid', 10, 2 );

function add_prefix_to_term_meta_by_mid( $value, $meta_id ) {
    if ( $meta_id == 789 ) {
        $value = 'Prefix - ' . $value;
    }
    return $value;
}

Modify comment meta value conditionally

Modify a comment meta value based on its meta ID and a condition.

add_filter( 'get_comment_metadata_by_mid', 'modify_comment_meta_conditionally', 10, 2 );

function modify_comment_meta_conditionally( $value, $meta_id ) {
    if ( $meta_id == 111 && some_condition() ) {
        $value = 'Modified Value';
    }
    return $value;
}

Apply a custom function to post meta value

Apply a custom function to a post meta value by its meta ID.

add_filter( 'get_post_metadata_by_mid', 'apply_custom_function_to_post_meta', 10, 2 );

function apply_custom_function_to_post_meta( $value, $meta_id ) {
    if ( $meta_id == 222 ) {
        $value = custom_function( $value );
    }
    return $value;
}