Unble to get save_post to work in wordpress

I have the following code to update the post_meta when a post is created. It is very simple,just storing the its own post_id in a meta field(might add more in the future)

The following code is not working, I guess it is because the $post_ID is blank, how do I pass the post_id of newly created post to the function update_postmeta (in function.php)?

//code from function.php
add_action('save_post', 'update_postmeta');
function update_postmeta($post_ID) {
update_post_meta($post_ID, 'related_id',$post_ID);
}

Related posts

Leave a Reply

1 comment

  1. Here is a good boilerplate for you:

    function update_postmeta($post_id) {
      global $post;
    
      // Post meta isn't sent for autosaves
      if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
      }
    
      update_post_meta($post->ID, 'related_id', $rand_id);
    }
    

    No where in your code is $rand_id defined though.