0

I wrote a custom plugin which inserts another metabox on the edit post screens. Once the user saves or publishes an article, I want to create another post with a custom post_type, which works great. However, data from other metaboxes are saved with the post_id of my newly created custom-typed-post instead of the original post. I suspect this is due to wp_insert_post() updating the global $post object with the post_id the function just generated.

But how can I make sure this does not happen? How to make sure, e.g. all other plugins also using the save_post hook save their data correctly to the right post instead of my custom-type-post created by wp_insert_post()?

add_action('save_post', array(&$this, 'save_post'), 1, 1);

public function save_post($post_id) {

            // verify if this is an auto save routine. 
            // If it is our form has not been submitted, so we dont want to do anything
            if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
                return;
            }


            if($_POST['post_type'] == self::POST_TYPE && current_user_can('edit_post', $post_id))
            {

                $newContestAdded = false;

                $_STBKT_assignedContestHopper = get_post_meta($post_id, '_STBKT_assignedContestHopper', true);
                if (($_STBKT_assignedContestHopper=='' || $_POST['STBKT_quickcontest_contestID']=='') 
                        && get_post_type($post_id) == 'post') { 
                    // Create contesthopper post object
                    $CH_post = array(
                      'post_title'    => '',
                      'post_content'  => '',
                      'post_status'   => 'publish',
                      'post_author'   => 1,
                      'post_type'     => 'contesthopper'
                    );

                    $_STBKT_assignedContestHopper = wp_insert_post( $CH_post, $wp_error );
                }
            }
}
0

I don't have time to thoroughly test this (and your code is not of the complete class anyway), so understand that there is a lot of guessing to this answer, but save_post will run again when you call wp_insert_post. I think it may be that second run that is causing the problem. If so, you should be able to avoid the issue by having your callback remove itself from the save _post hook.

add_action('save_post', array(&$this, 'save_post'), 1, 1);

public function save_post($post_id) {
    remove_action('save_post', array(&$this, 'save_post'), 1, 1);

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.