admin管理员组

文章数量:1332339

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 ?

Thanks

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 ?

Thanks

Share Improve this question edited Jun 21, 2020 at 18:52 Mort 1305 9835 silver badges18 bronze badges asked Jun 21, 2020 at 17:53 DavidGDavidG 12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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

https://developer.wordpress/reference/hooks/save_post/

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 ) )
        return;

        $value = 'your value';

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

    }

}
add_action( 'save_post', 'my_update_on_save', 10, 2 );

本文标签: phpHow to edit post meta data before publishing the post it self wordpress