save_post + insert_post = infinite loop

All we need is an easy explanation of the problem, so here it is.

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 );
    }
}

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply