WordPress.org

Make WordPress Core

Opened 3 years ago

Closed 6 months ago

#23839 closed defect (bug) (invalid)

wp_insert_post() duplicate insertions

Reported by: mikemayhem3030 Owned by:
Milestone: Priority: normal
Severity: normal Version: 3.5.1
Component: Posts, Post Types Keywords: reporter-feedback
Focuses: Cc:

Description

Hello

I've read this on an older ticket and it was closed. However I'm having a problem with this. I have developed plugins that insert new posts via use of a loop.

The loop runs through 10 times for example, however 20 new posts are created, with duplicate entries.

All I can figure out is this is a bug in wordpress with wp_insert_post()??

Change History (12)

#1 @alexvorn2
3 years ago

  • Keywords close added; needs-patch removed

To know if this is a bug we need to replicate this, but I'm sure 90% that you did something wrong...

#2 @mikemayhem3030
3 years ago

Hello

How can you be that sure I've done something wrong?

      $j=0;    

      foreach($pictures as $picture){                   
                $the_img = wp_get_attachment_image_src( $picture->ID,"full" );
                
                $title = get_post_meta($picture->ID, '_wp_attached_file',true);			
       	        if (!get_page_by_title($title, 'OBJECT', 'picsmash') ){
                             $my_post = array(
                             'post_title' => $title,
                             'post_status' => 'publish',
                             'post_type' => 'picsmash',
                              );
                        
                            #} Insert the post into the database
                             $post_id = wp_insert_post( $my_post );
            
                            
                            }
			$j++;
					  
                    
                }

That's my code. If I output $j it is outputting the correct number of pictures, however when I then view the custom post type - it has double the number of posts.

It seems to be caused by the fact this is in a function, and I run it using AJAX.

I would imagine if I change it so it's not AJAX related it would probably work OK. But it's not as slick that way.

Cheers

Mike

Last edited 3 years ago by SergeyBiryukov (previous) (diff)

#3 @mikemayhem3030
3 years ago

  • Keywords needs-patch needs-testing added; close removed

#4 @SergeyBiryukov
3 years ago

  • Keywords reporter-feedback added; needs-patch needs-testing removed

Could you provide the full code to reproduce the issue, including the JS function that makes an AJAX request, the PHP function that handles it, and the custom post type registration?

#5 @alexvorn2
3 years ago

can you try other browser and see if the problem occurs...

#6 follow-up: @alexvorn2
3 years ago

related = #11081

#7 in reply to: ↑ 6 ; follow-up: @mikemayhem3030
3 years ago

Replying to alexvorn2:

related = #11081

The related ticket I couldn't see how I could use this to help prevent what's happening. It seems pretty random (i.e. it doesn't duplicate them every single time, but most times it will).

PHP handler function:-

function picsmash_get_all_pics(){
    
            global $wp, $wpdb; 
			
            $j = 1;
            wp_reset_query(); 
            $querystr = "SELECT DISTINCT * FROM $wpdb->posts WHERE post_status != 'trash' AND post_type = 'attachment' AND (post_mime_type = 'image/jpeg' OR post_mime_type = 'image/gif' OR post_mime_type = 'image/png')";
            $pictures = $wpdb->get_results($querystr);

            foreach($pictures as $picture){
                    
                $the_img = wp_get_attachment_image_src( $picture->ID,"full" );
                $img_full = $the_img[0];
                $ID = $picture->ID;
                
                $title = get_post_meta($picture->ID, '_wp_attached_file',true);
				
				$querystr = "SELECT ID FROM $wpdb->postmeta WHERE meta_value = $title";
     			$added = $wpdb->get_col($querystr);

       	        if (!get_page_by_title($title, 'OBJECT', 'picsmash')){

                             $my_post = array(
                             'post_title' => $title,
                             'post_status' => 'publish',
                             'post_type' => 'picsmash',
                              );
                        
                            #} Insert the post into the database
                             $post_id = wp_insert_post( $my_post );
     
                            
                            }
						$j++;
					  
                    
                }
                


            $result['message'] = $j . " new images added to the Pics Mash</b>";
            
            echo $result['message'];

            die();
    
}


add_action('wp_ajax_picsmash_get_all_pics', 'picsmash_get_all_pics');

JS request:-

	$('#ps-ajax').submit(function(){
		$('#feedback').html('<div class="loading"><img src="' + window.loadingImg + '" alt="" title="Adding pics" /><br />Adding pics...</div>').fadeIn(1000);
			data = {
			action: 'picsmash_get_all_pics'
			};
			$.post(ajaxurl, data, function(response){
			$('#feedback').html(response);
		});
		return false;
	});

Post type reg:-

    #} Custom post types - pics
    $labels = array(
                'name' => _x('Pics Mash', 'post type general name','PicsMash'),
                'singular_name' => _x('Pics Mash', 'post type singular name','PicsMash'),
                'add_new' => _x('Manually Add Pic', 'pic','PicsMash'),
                'add_new_item' => __('Manually Add New Pic','PicsMash'),
                'edit_item' => __('Edit Pic','PicsMash'),
                'new_item' => __('New Pic','PicsMash'),
                'view_item' => __('View Pic','PicsMash'),
                'search_items' => __('Search Pics','PicsMash'),
                'not_found' =>  __('No pics found','PicsMash'),
                'not_found_in_trash' => __('No pics found in Trash','PicsMash'),
                'parent_item_colon' => '',
                'menu_name' => 'Pics Mash'
            );
    $args = array(
                'labels' => $labels,
                'public' => true,
                'publicly_queryable' => true,
                'show_ui' => true,
                'show_in_menu' => true,
                'query_var' => true,
                'rewrite' => array( 'slug' => 'picsmash','with_front' => FALSE ),
                'capability_type' => 'post',
                'has_archive' => true,
                'hierarchical' => false,
                'menu_icon' => plugins_url('/i/image.png',__FILE__),
                'menu_position' => null,
                'supports' => array( 'title', 'author','comments')
            );
    #} Register it
    register_post_type('picsmash',$args);

#8 in reply to: ↑ 7 ; follow-up: @alexvorn2
3 years ago

Replying to mikemayhem3030:


Add this condition and see if it helps:

if ( true === DOING_CRON || true === DOING_AJAX )
    return;


#9 in reply to: ↑ 8 @mikemayhem3030
3 years ago

Replying to alexvorn2:

Replying to mikemayhem3030:


Add this condition and see if it helps:

if ( true === DOING_CRON || true === DOING_AJAX )
    return;


Where would I add that too? - which place in the code?

Version 0, edited 3 years ago by mikemayhem3030 (next)

#10 @nacin
3 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to invalid
  • Status changed from new to closed

Please try the support forums. "wp_insert_post() duplicate insertions" is not a bug and is invalid.

#11 follow-up: @cakePlease
9 months ago

  • Resolution invalid deleted
  • Status changed from closed to reopened

Im having the same problem, and a search online shows many others are as well. There doesnt seem to be a solution though.

A use case for something like this could be, looping through an web service data source (eg tumblr/twitter/fb/etc) and inserting that as posts into WP. This script is executed via a server cron (not WP cron). Each loop iteration should add 1 post, but in fact it adds multiple entries of the same post.

This has to be a bug.

#12 in reply to: ↑ 11 @SergeyBiryukov
6 months ago

  • Component changed from General to Posts, Post Types
  • Resolution set to invalid
  • Status changed from reopened to closed

Replying to cakePlease:

A use case for something like this could be, looping through an web service data source (eg tumblr/twitter/fb/etc) and inserting that as posts into WP. This script is executed via a server cron (not WP cron). Each loop iteration should add 1 post, but in fact it adds multiple entries of the same post.

Apparently the script runs into some kind of a race condition.

Please try the support forums to get help with your issue: https://wordpress.org/support/.

Note: See TracTickets for help on using tickets.