August 28, 2015 — kyle.huynh205
Avoiding infinite loops when using “save_post” action hook
Original link : here
If you are calling a function such as wp_update_post that includes the save_post hook, your hooked function will create an infinite loop. To avoid this, unhook your function before calling the function you need, then re-hook it afterward.
<?php
// this function makes all posts in the default category private
function set_private_categories($post_id) {
// If this is a revision, get real post ID
if ( $parent_id = wp_is_post_revision( $post_id ) )
$post_id = $parent_id;
// Get default category ID from options
$defaultcat = get_option( 'default_category' );
// Check if this post is in default category
if ( in_category( $defaultcat, $post_id ) ) {
// unhook this function so it doesn't loop infinitely
remove_action( 'save_post', 'set_private_categories' );
// update the post, which calls save_post again
wp_update_post( array( 'ID' => $post_id, 'post_status' => 'private' ) );
// re-hook this function
add_action( 'save_post', 'set_private_categories' );
}
}
add_action( 'save_post', 'set_private_categories' );
?>
NOTE: It is very important to use the same parameters in remove_action than in add_action. Example with priority below (extract)… if the parameters are not the same, the infinite loop occurs…
// unhook this function so it doesn't loop infinitely remove_action( 'save_post', 'set_private_categories', 13, 2 ); // update the post, which calls save_post again wp_update_post( array( 'ID' => $post_id, 'post_status' => 'private' ) ); // re-hook this function add_action( 'save_post', 'set_private_categories', 13, 2 ); } } add_action( 'save_post', 'set_private_categories', 13, 2 );