LeoLopesWeb
12/13/2019 - 12:47 AM

WordPress - Update post programmatically when a post is saved

<?php 
function update_on_post_saved( $post_id ) {
    if ( wp_is_post_revision( $post_id ) ) return;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    // if ('NNN' !== $_POST['post_type']) return; return if post type is not NNN
    // unhook this function so it doesn't loop infinitely
    remove_action('save_post', 'update_on_post_saved');
    // Update post
    $my_post = [
      'ID'           => $post_id,
      'post_content' => 'Put content here',
    ];
    // Update the post into the database
    wp_update_post( $my_post );
    // re-hook this function
    add_action('save_post', 'update_on_post_saved');
}
add_action( 'save_post', 'update_on_post_saved' );