Using WordPress ‘pre_post_update’ PHP action

The pre_post_update WordPress PHP action fires immediately before an existing post is updated in the database.

Usage

add_action('pre_post_update', 'your_custom_function', 10, 2);

function your_custom_function($post_id, $data) {
    // Your custom code here
}

Parameters

  • $post_id (int): The ID of the post being updated.
  • $data (array): An array of unslashed post data.

More information

See WordPress Developer Resources: pre_post_update

Examples

Logging post updates

Log post updates to a custom log file.

add_action('pre_post_update', 'log_post_update', 10, 2);

function log_post_update($post_id, $data) {
    $log_message = 'Updating post ID: ' . $post_id . ' - ' . $data['post_title'];
    error_log($log_message, 3, '/var/www/html/your-log-file.log');
}

Modifying post content before updating

Add a custom prefix to post titles before updating the post.

add_action('pre_post_update', 'modify_post_title', 10, 2);

function modify_post_title($post_id, $data) {
    $data['post_title'] = 'Custom Prefix: ' . $data['post_title'];
    // Update the post with the modified title
    wp_update_post($data);
}

Prevent post updates for a specific user role

Disallow post updates for users with the ‘subscriber’ role.

add_action('pre_post_update', 'prevent_post_update_for_subscribers', 10, 2);

function prevent_post_update_for_subscribers($post_id, $data) {
    $user = wp_get_current_user();
    if (in_array('subscriber', $user->roles)) {
        wp_die('Sorry, subscribers are not allowed to update posts.');
    }
}

Send email notification on post update

Send an email notification to the admin when a post is updated.

add_action('pre_post_update', 'send_email_on_post_update', 10, 2);

function send_email_on_post_update($post_id, $data) {
    $to = get_option('admin_email');
    $subject = 'Post Updated: ' . $data['post_title'];
    $message = 'The post with ID ' . $post_id . ' has been updated.';
    wp_mail($to, $subject, $message);
}

Schedule a custom event on post update

Schedule a custom event to run after a post is updated.

add_action('pre_post_update', 'schedule_custom_event', 10, 2);

function schedule_custom_event($post_id, $data) {
    if (!wp_next_scheduled('your_custom_event', array($post_id))) {
        wp_schedule_single_event(time() + 3600, 'your_custom_event', array($post_id));
    }
}

Remember to add the custom event action:

add_action('your_custom_event', 'your_custom_event_function', 10, 1);

function your_custom_event_function($post_id) {
    // Your custom code here
}