Advertisement
5ally

Untitled

Sep 26th, 2018
1,198
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.89 KB | None
  1. <?php
  2. // $old_value is just for testing purposes, and should be removed.
  3. function wpse315119_meta_trick( $filter, $object_id, $meta_key, $meta_value, $unique_or_prev_value, $old_value = null ) {
  4.     // Remove the filters and save the new meta value. Make sure that
  5.     // the priority and number of arguments are exactly the same as
  6.     // when you added the filters.
  7.     remove_filter('add_post_metadata', 'wpse22728_meta', 20, 5);
  8.     remove_filter('update_post_metadata', 'wpse22728_meta', 20, 5);
  9.  
  10.     // Manually save the meta data.
  11.     if ( 'add_post_metadata' === $filter ) {
  12.         add_metadata( 'post', $object_id, $meta_key, $meta_value, $unique_or_prev_value );
  13.         echo 'Meta data added. Value is "' . $meta_value . '" and not "' . $old_value . '".<br>'; // test
  14.     }
  15.     elseif ( 'update_post_metadata' === $filter ) {
  16.         update_metadata( 'post', $object_id, $meta_key, $meta_value, $unique_or_prev_value );
  17.         echo 'Meta data updated. Value is "' . $meta_value . '" and not "' . $old_value . '".<br>'; // test
  18.     }
  19.  
  20.     // Finally, re-add the filters.
  21.     add_filter('add_post_metadata', 'wpse22728_meta', 20, 5);
  22.     add_filter('update_post_metadata', 'wpse22728_meta', 20, 5);
  23. }
  24.  
  25. function wpse22728_meta($check, $object_id, $meta_key, $meta_value, $unique_or_prev_value) {
  26.     $the_filter = current_filter(); // keep this and don't change
  27.     if( get_post_type($object_id) == 'mycpt' ) {
  28.         if( $meta_key == 'mycustomkey' ) {
  29.             $old_value = $meta_value;
  30.  
  31.             // Change the value.
  32.             $meta_value = 'new_value';
  33.  
  34.             // Save the new value.
  35.             wpse315119_meta_trick( $the_filter, $object_id, $meta_key, $meta_value, $unique_or_prev_value, $old_value );
  36.  
  37.             // Finally, set $check to the saved value, so that the $old_value won't be saved.
  38.             $check = $meta_value;
  39.         }
  40.     }
  41.     return $check;
  42. }
  43.  
  44. add_filter('add_post_metadata', 'wpse22728_meta', 20, 5);
  45. add_filter('update_post_metadata', 'wpse22728_meta', 20, 5);
Advertisement
RAW Paste Data Copied
Advertisement