Endless loop with wp_insert_post and wp_update_post

I have an array $unqiues which contains URL’s, I loop over the array with the code below to get the URL titles, insert a new post, update the post meta. Then I change the the posts title and name to the $pid which was returned by wp_insert_post.

This created an endless loop, I have about 600 or fewer URL’s in the $unique array. I just hit 75,000 queries within an hour on my host and have to wait an hour for the limit to reset. What caused the endless loop? This code worked when I tested with 10 URL’s in the array.

Read More

How can this be written more efficiently?

Thanks

foreach($uniques as $unique){
      $pagetitle = getTitle($unique);
      $new_post = array(
            'post_title' => $unique,
            'post_status'   => 'publish',
            'post_type' => 'websites'
        );
        $pid = wp_insert_post($new_post);

        update_post_meta($pid,'title', $pagetitle);
        update_post_meta($pid,'url',$unique);


          $my_post = array(
              'ID'           => $pid,
              'post_title' => $pid,
              'post_name' => $pid
          );

          wp_update_post( $my_post );
}

Related posts

1 comment

  1. It sure can be written in a more efficient way (untested):

    $added = array();
    global $wpdb;
    foreach($uniques as $unique){
      $pagetitle = getTitle($unique);
      $new_post = array(
        'post_title' => $unique,
        'post_status' => 'publish',
        'post_type' => 'websites'
      );
      $pid = wp_insert_post($new_post);
      if ($pid) {
        $wpdb->query( $wpdb->prepare(
          "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) VALUES
           (%d, '%s', '%s'), (%d, '%s', '%s')",
           $pid, 'title', $pagetitle, $pid, 'url', $unique
        ) );
        $added[] = $pid;
      }
    }
    if ( ! empty($added) ) {
       $ids = implode(',', $added); 
       $wpdb->query("UPDATE $wpdb->posts SET `post_title` = `ID`, `post_name` = `ID` WHERE `ID` IN ($ids)");
    }
    

    With 600 urls this code runs 1200 queries less than your, but maybe is not enough…

Comments are closed.