9

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?

1 Answer 1

8

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; 
}
1
  • 1
    Yes, it was this infinite recurive problem that I had already encountered as well. Awesome help thanks! Oct 9, 2014 at 8:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.