How to Avoid Infinite Loop with save_post Callback in WordPress

While working on one of my clients projects, I had to modify the post title and add some string at its end before saving it to the database. So, I hooked into save_post action and updated the title using wp_update_post function. The code looked something like this,

Useful Read: Restricting Users to View Only Their Own Media Library Items

add_action( 'save_post', 'ccw_update_post_title' );

function ccw_update_post_title( $post_id ) {
	$title = get_the_title( $post_id );
	$title = $title.' Some random string';
	$args = array(
		'ID'              => $post_id,
		'post_title'      => $title
	);
		
	wp_update_post( $args );
}

It looks pretty straightforward, but there is a major problem associated with this code.

Whenever save_post action is triggered the ccw_update_post_title function calls wp_update_post method. Now, whenever wp_update_post function is called save_post action is triggered which will again lead to calling wp_update_post and resulting in an infinite loop.

In order to fix this issue, you need to remove the action before calling wp_update_post, then again re-hook afterwards.

add_action( 'save_post', 'ccw_update_post_title' );

function ccw_update_post_title( $post_id ) {

	$title = get_the_title( $post_id );
	$title = $title.' Some random string';
	$args = array(
		'ID'              => $post_id,
		'post_title'      => $title
	);

	// unhook this function so it doesn't loop infinitely
	remove_action( 'save_post', 'ccw_update_post_title' );
	
	wp_update_post( $args );

        // re-hook this function
	add_action( 'save_post', 'ccw_update_post_title' );
}

 

0 Comments

Leave a Comment.