The post_updated WordPress PHP action fires once an existing post has been updated.
Usage
add_action('post_updated', 'your_custom_function', 10, 3);
function your_custom_function($post_id, $post_after, $post_before) {
// your custom code here
}
Parameters
$post_id(int) – Post ID.$post_after(WP_Post) – Post object following the update.$post_before(WP_Post) – Post object before the update.
More information
See WordPress Developer Resources: post_updated
Examples
Send an email notification when a post is updated
Send an email to the admin when a post is updated:
add_action('post_updated', 'send_email_on_post_update', 10, 3);
function send_email_on_post_update($post_id, $post_after, $post_before) {
$to = get_option('admin_email');
$subject = 'A post has been updated';
$message = 'The post with ID ' . $post_id . ' has been updated.';
wp_mail($to, $subject, $message);
}
Log post changes
Log the changes made to a post by comparing the post_before and post_after objects:
add_action('post_updated', 'log_post_changes', 10, 3);
function log_post_changes($post_id, $post_after, $post_before) {
if ($post_before->post_title !== $post_after->post_title) {
error_log('Post ' . $post_id . ' title changed from "' . $post_before->post_title . '" to "' . $post_after->post_title . '"');
}
}
Clear cache for a post when it’s updated
Clear cache related to a specific post when it’s updated:
add_action('post_updated', 'clear_post_cache', 10, 3);
function clear_post_cache($post_id, $post_after, $post_before) {
// Assuming you have a cache function called clear_cache
clear_cache($post_id);
}
Update post meta based on the post update
Update a custom post meta field when a post is updated:
add_action('post_updated', 'update_custom_post_meta', 10, 3);
function update_custom_post_meta($post_id, $post_after, $post_before) {
if ($post_before->post_content !== $post_after->post_content) {
update_post_meta($post_id, 'content_last_updated', current_time('mysql'));
}
}
Trigger an action only when a specific post type is updated
Trigger an action only when a custom post type ‘book’ is updated:
add_action('post_updated', 'custom_post_type_update', 10, 3);
function custom_post_type_update($post_id, $post_after, $post_before) {
if ($post_after->post_type === 'book') {
// your custom code here
}
}