0

I'm currently trying to create/update one post while also saving the current post that I'm on. It's all happening here:

add_action('save_post', 'wysiwyg_save_meta');
function wysiwyg_save_meta(){
    global $post;
    $editor_id = WYSIWYG_EDITOR_ID;
    $meta_key = WYSIWYG_META_KEY;

    if(isset($_REQUEST[$editor_id])) {
        update_post_meta($post->ID, WYSIWYG_META_KEY, $_REQUEST[$editor_id]);

        $thankYouPost = get_thank_you_post($post->ID);

        $postArgs = array(
            'post_content'   => $_REQUEST[$editor_id], 
            'post_name'      => 'thank-you',
            'post_title'     => "Thank You",
            'post_status'    => $post->post_status,
            'post_type'      => 'landing_page',
            'post_parent'    => $post->ID,
        );

        if ($thankYouPost->ID) {
            $postArgs['ID'] = $thankYouPost->ID;
        }
        wp_reset_postdata();
        wp_reset_query();
        wp_insert_post($postArgs);
        wp_reset_postdata();
        wp_reset_query();
    }
}

Now, this works and saves both pages, but it doesn't seem like it's actually working. The page just sits and tries to load and eventually I get back a 502 Bad Gateway error. However, manually refreshing the page shows me that the action was successful.

What could be causing this? Any more information I will be happy to provide. Thank you for your time.

1

As pointed out by Otto - it's going to cause an infinite loop. The solution is to unhook your function before you do a wp_insert_post and then hook it back on afterwards.

remove_action('save_post', 'wysiwyg_save_meta');
wp_insert_post($postArgs);
add_action('save_post', 'wysiwyg_save_meta');
1

Hate to point out the obvious but:

add_action('save_post', 'wysiwyg_save_meta');
function wysiwyg_save_meta(){
...
        wp_insert_post($postArgs);
...
}

That's an infinite loop.

The save_post action is called at the end of wp_insert_post. So you're just looping around in circles, digging an ever deeper hole of calling your function and then wp_insert_post over and over again, until you eat up all available memory or the process times out.

  • Thanks. Do I need to just add a new save_post action containing my wp_insert_post function? Or do I need to test for something completely different and then call wp_insert_post? – Domenic Fiore Sep 5 '14 at 20:50
  • I think the real point is to not call wp_insert_post from inside a function hooked to the save_post action at all. You're making a recursive loop here. You need to either break the loop or not start it to begin with. – Otto Sep 5 '14 at 22:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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