2

I want to add a meta value to my post , which will be based on another meta value , before publish post . This is what I have tried

add_action('save_post_my_custom_post', 'add_custom_field_automatically' );
function add_custom_field_automatically($post_ID) { 

    $new_meta_value = get_post_meta($post_ID,'_my_meta_key',TRUE).'to ' .' something new';

    add_post_meta($post_ID, '_my_new_meta_key', $new_meta_value, true);
}

But it doesn't work . The hook fired properly , it saves only "to something new" , but what I expect the value should be "my meta value to something new"

  • Which hook it is save_my_custom_post ? – Sumit May 16 '16 at 12:58
  • here my_custom_post is the name of my custom post type . Technically it is the 'save_post' hook . – Mithun Sarker Shuvro May 16 '16 at 13:09
  • Can you elaborate by "doesn't work" - have you checked that the hook is definitely firing (use error logging to debug)? Is it saving data but not what you expected? – TheDeadMedic May 16 '16 at 13:12
  • Oh! then it should be save_post_my_custom_post because hook name is save_post_{post_type} – Sumit May 16 '16 at 13:22
  • @Sumit sorry , my bad , I have edited my question , it still doesn't work . – Mithun Sarker Shuvro May 16 '16 at 13:28
2

The solution is using added_post_meta and updated_post_meta hook .

Here is the working code .

add_action( 'added_post_meta', 'add_custom_field_automatically', 10, 4 );
add_action( 'updated_post_meta', 'add_custom_field_automatically', 10, 4 );
function add_custom_field_automatically( $meta_id, $post_id, $meta_key, $meta_value )
{
    if ( '_my_meta_key' == $meta_key ) {

        add_post_meta($post_id, '_my_new_meta_key', $meta_value.'to something new', true);
    }
}
-1

Use global $post at the top of the page just before the function start

global $post;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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