-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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