Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[WordPress] How to update a post during the save hook without getting stuck in an infinite loop.
<?php
add_action( 'save_post', 'acme_update_post' );
/**
* An example for how to update the title of the post during the
* save_post action in order to prevent infinite loops from
* occurring.
*
* @param int $post_id The ID of the post that's being updated
*/
function acme_update_post( $post_id ) {
// First we read the title and encode it
$title = get_the_title( $post_id );
// Next, we look to see if a certain word is present in the title
if ( 0 < strpos( $title, "Rick Roll" ) ) {
// We unhook this action to prevent an infinite loop
remove_action( 'save_post', 'acme_update_post' );
// Update the title so that it doesn't include Rick Roll
$title = str_ireplace( "Rick Roll", "", $title );
$args = array(
'ID' => $post_id,
'post_title' => $title
);
wp_update_post( $args );
// Now hook the action
add_action( 'save_post', 'acme_update_post' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.