Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // $old_value is just for testing purposes, and should be removed.
- function wpse315119_meta_trick( $filter, $object_id, $meta_key, $meta_value, $unique_or_prev_value, $old_value = null ) {
- // Remove the filters and save the new meta value. Make sure that
- // the priority and number of arguments are exactly the same as
- // when you added the filters.
- remove_filter('add_post_metadata', 'wpse22728_meta', 20, 5);
- remove_filter('update_post_metadata', 'wpse22728_meta', 20, 5);
- // Manually save the meta data.
- if ( 'add_post_metadata' === $filter ) {
- add_metadata( 'post', $object_id, $meta_key, $meta_value, $unique_or_prev_value );
- echo 'Meta data added. Value is "' . $meta_value . '" and not "' . $old_value . '".<br>'; // test
- }
- elseif ( 'update_post_metadata' === $filter ) {
- update_metadata( 'post', $object_id, $meta_key, $meta_value, $unique_or_prev_value );
- echo 'Meta data updated. Value is "' . $meta_value . '" and not "' . $old_value . '".<br>'; // test
- }
- // Finally, re-add the filters.
- add_filter('add_post_metadata', 'wpse22728_meta', 20, 5);
- add_filter('update_post_metadata', 'wpse22728_meta', 20, 5);
- }
- function wpse22728_meta($check, $object_id, $meta_key, $meta_value, $unique_or_prev_value) {
- $the_filter = current_filter(); // keep this and don't change
- if( get_post_type($object_id) == 'mycpt' ) {
- if( $meta_key == 'mycustomkey' ) {
- $old_value = $meta_value;
- // Change the value.
- $meta_value = 'new_value';
- // Save the new value.
- wpse315119_meta_trick( $the_filter, $object_id, $meta_key, $meta_value, $unique_or_prev_value, $old_value );
- // Finally, set $check to the saved value, so that the $old_value won't be saved.
- $check = $meta_value;
- }
- }
- return $check;
- }
- add_filter('add_post_metadata', 'wpse22728_meta', 20, 5);
- add_filter('update_post_metadata', 'wpse22728_meta', 20, 5);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement