skip to Main Content

I use a hook edit_post_(post_type). After updating a record, I get two new records at once when I only need one. What am I doing wrong?

add_action('edit_post_applications', 'add_new_university');

function add_new_university($id)
{
    $post_field = get_fields($id);

    return wp_insert_post(array(
        'post_type' => 'institution',
        'post_title' => get_post($id)->post_title,
        'post_status' => 'publish',
        'meta_input' => array(
            'full_name'                          => $post_field['full_name'],
            'short_name'                         => $post_field['short_name']
        ),
    ));
}

I tried different hooks but couldn’t fix this problem

3

Answers


  1. Chosen as BEST ANSWER

    Thank you. This helped:

        if (get_post_meta($post_id, '_university_added', true)) return;
    
    
        $post_field = get_fields($post_id);
        wp_insert_post([
            'post_type' => 'institution',
            'post_title' => get_the_title($post_id),
            'post_status' => 'publish',
            'meta_input' => [
                'full_name' => $post_field['full_name'],
                'short_name' => $post_field['short_name']
            ],
        ]);
        update_post_meta($post_id, '_university_added', true);
    
    

  2. The edit_post hook (and similar hooks) can be triggered multiple times during a single post save operation. This can happen due to various reasons like revisions, autosaves, or other plugins/themes interacting with the save process.

    add_action('save_post_applications', 'add_new_university', 10, 3);
    
    function add_new_university($post_id, $post, $update) {
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
        if (wp_is_post_revision($post_id)) return;
        if (!$update) return;
        if (get_post_meta($post_id, '_university_added', true)) return;
    
        $post_field = get_fields($post_id);
        wp_insert_post([
            'post_type' => 'institution',
            'post_title' => get_the_title($post_id),
            'post_status' => 'publish',
            'meta_input' => [
                'full_name' => $post_field['full_name'],
                'short_name' => $post_field['short_name']
            ],
        ]);
        update_post_meta($post_id, '_university_added', true);
    }
    

    Added checking for autosave, revision, update and checking if already processed (by using post metadata).

    Login or Signup to reply.
  3. Another solution to the problem is to add a check

        $posts = get_posts(['post_type' => 'institution']);
        foreach ($posts as $post) {
            if ($post->post_title == get_post($id)->post_title)
                return;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search