简体   繁体   中英

Modify custom field after save_post

In my custom post type, once the user saves the post, is there a way to check the value of one of the fields and update it? The value I will insert will depend on the post's ID so save_post needs to be used in case it's a new post.

Yes you can have all of your data from $_POST or global $post after you save or update the post using save_post hook as you mentioned in your question

add_action( 'save_post', 'afterSavePost' );
function afterSavePost($pid)
{
    $postId=$pid; 
    // or
    global $post;
    $postId=$post->ID;
    $postTitle=$post->post_title; 
    // or
    $postId=$_POST['ID'];
    $postTitle=$_POST['post_title']; 
}

You mentioned custom field and in that case you can use

$yourCustomField=get_post_meta($postId, 'your_custom_field',true); // get a custom field

and

$yourCustomField="New value";
update_post_meta($postId, 'your_custom_field', $yourCustomField); // update a custom field

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM