Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created March 26, 2015 12:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tommcfarlin/1f67140263a8bd8c22f3 to your computer and use it in GitHub Desktop.
Save tommcfarlin/1f67140263a8bd8c22f3 to your computer and use it in GitHub Desktop.
[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