How to use update_{$meta_type}_metadata filter to modify meta value

All we need is an easy explanation of the problem, so here it is.

I’m trying to wrap my head around the update_{$meta_type}_metadata filter, in order to modify both post and user metadata before database insertion.

After reading the docs and the core, it seems to me the filter must return null for the add_metadata function to continue. However, this means it is impossible to filter the $meta_value since returning a non-null value short-circuits the function.

What am I missing here? And, more generally, what is the point of having the filter at all when it can only return null?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The code snippet in question is:

$check = apply_filters( "update_{$meta_type}_metadata", 
    null, $object_id, $meta_key, $meta_value, $prev_value );
if ( null !== $check )
    return (bool) $check;

This filter only allows you to prevent the updating of the metadata for a given type, not to explicitly change the metadata itself.

If you want to use this filter to modify the metadata, you could try for example:

add_filter( 'update_post_metadata', 'wpse_163859', 10, 5 );
update_post_meta( $post_id = 123, 'test', 'ABCDEF' );

where:

function wpse_163859( $check, $object_id, $meta_key, $meta_value, $prev_value )
{
    // Avoid infinite recursion:
    remove_filter( current_filter(), __FUNCTION__ ); 

    // Modify the meta value;
    $meta_value = strtolower( $meta_value ); 

    // Do something else ...

    // Update the modified value.
    update_post_meta( $object_id, $meta_key, $meta_value, $prev_value ); 

    // Return something else than null
    return true; 
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply