Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 );
    }
}
share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

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.

share|improve this answer
    
That worked like a charm, thanks for the detailed explanation - you're my hero for today! –  ptriek Nov 23 '11 at 13:08
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.