Skip to content

Instantly share code, notes, and snippets.

@fgilio
Last active April 17, 2024 22:34
Show Gist options
  • Select an option

  • Save fgilio/38dfbf9d03654b21302a to your computer and use it in GitHub Desktop.

Select an option

Save fgilio/38dfbf9d03654b21302a to your computer and use it in GitHub Desktop.
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' );
@fgilio
Copy link
Copy Markdown
Author

fgilio commented Jun 6, 2023

Glad it helped!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment