I’m trying to automatically create a new post when a post containing a certain custom field is saved – hooking an insert_post function into save_post.
This generates an infinite loop.
I found some answers to this problem, suggesting I should check the post type before inserting.
However, the following code still gives an infinite loop, any ideas?
add_action('save_post', 'createGallery');
function createGallery () {
global $post;
if ( $post->post_type == 'activity' ) {
$gallerypost = array(
'post_content' => 'the text of the post',
'post_status' => 'publish',
'post_title' => 'Photo album',
'post_type' => 'post',
'post_author' => 1);
wp_insert_post( $gallerypost );
}
}
This is because the first time you go round the loop $post
is the current post. But the second time you go around the loop, $post has not changed. The same thing happens the 3rd, 4th, 5th, etc
Because the $post variable is the current post of that page, not the post you’ve just saved/inserted, the loops if statement will always be true, and an infinite loop entails. Instead of checking the $post
variable, you should check the ID of the post that is being saved. If we look at the call that executes the action save_post
:
do_action('save_post', $post_ID, $post);
We now see that save_post has parameters!! So if we indicate when adding that the function accepts 1 parameters:
add_action('save_post', 'createGallery',1,1);
Then add the post ID parameter and use that instead:
function createGallery ($post_ID) {
if ( get_post_type($post_ID) == 'activity' ) {
$gallerypost = array(
'post_content' => 'the text of the post',
'post_status' => 'publish',
'post_title' => 'Photo album',
'post_type' => 'post',
'post_author' => 1);
wp_insert_post( $gallerypost );
}
}
Then your infinite loop should be gone! If it isn’t then you’ve made a considerable leap towards making your code more accurate since you are now working on the correct data.
I would warn that changing 'post_type' => 'post',
to 'post_type' => 'activity',
would reintroduce the infinite loop.