I've a custom field in a custom post type whose value I want to calculate dynamically before publishing the post itself for the first time and this custom field gets stored in the postmeta table. How can I achieve this desired functionality to edit or modify post_meta data before saving or publishing the post ?


1 Answer 1


You can use save_post action which gets triggered when a post is created or updated.


In your function, you will have to check for your custom post type, set the value you would like to have to a variable, and pass it to the update_post_meta function with giving the name of your custom field.

function my_update_on_save( $post_id ) {

   if ( get_post_type($post_id) == 'your_custom_post_type' ) {

        // Do nothing if this is a post revision
        if ( wp_is_post_revision( $post_id ) )

        $value = 'your value';

        update_post_meta($post_id, 'your_custom_field_name', $value);


add_action( 'save_post', 'my_update_on_save', 10, 2 );
  • This doesn't work. I've tried it already. It even triggers when you click on And New post button
    – DavidG
    Commented Jun 21, 2020 at 20:07

Your Answer

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

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