wp_insert_post fails at return statement (nothing is returned to the caller, the error displayed is: The Link You Followed Has Expired)

there is a WooCommerce site where we try to add the Wholesale Pro plugin, which upon activation creates two pages (login, store). For this task it calls the wp_insert_post from a static method. The wp_insert_post does its stuff, and we even log every part of the wp_insert_post procedure to debug.log, comes down to return statement and then the WordPress fails with "The Link You Followed Has Expired" on the plugins.php screen. The return statement returns nothing to the caller static method, but the page/post is created in wp_posts table.

The plugin itself is proven to activate and work properly on another site.

wp_insert_post order problem

I’m sorry, I speak a little English.

My code in my custom theme (functions.php) [only example]:

$  posts = array( '141th', // ... '3rd', '2nd', '1st' ); foreach( $  posts as $  post ) { wp_insert_post( array( 'post_title'=> $  post ) ); } 

My posts list:

141 139 140 137 138 ... 1 

I would like (in order):

141 140 139 138 ... 1 

Why? What is the problem and how to solving?

Thanks.

wp_insert_post not inserting post from XML

I’m using below to read XML file and import its content as a page in wordpress, but it’s not working:

add_action('import_demo', 'importIt'); function importIt(){     // The code until now     $  path = get_template_directory() . '/demo/pages.xml';     $  xml = simplexml_load_file($  path);     foreach ($  xml->channel->item as $  item) {         $  postCreated = array(             'post_title'    => $  item->title,             'post_content'  => $  item->content,             // 'post_excerpt'  => $  item->excerpt,             'post_status'   => 'publish',             'post_type'     => 'page', // Or "page" or some custom post type         );          $  postInsertId = wp_insert_post( $  postCreated );          add_action('add_attachment','featuredImageTrick');         media_sideload_image($  item->image, $  postInsertId, $  item->title);         remove_action('add_attachment','featuredImageTrick');          function featuredImageTrick($  att_id){             $  p = get_post($  att_id);              update_post_meta($  p->post_parent,'_thumbnail_id',$  att_id);         }     } } 

WordPress wp_insert_post() returns 0 but not not wp_error

wp_insert_post() return value says:

(int|WP_Error) The post ID on success. The value 0 or WP_Error on failure.

Okay, I’ have an import routine running and all but a few (about 20) of them import correctly. The ones that fail have a return value of 0 but is_wp_error() is NOT true. How do I find out what happened and why these certain articles won’t import properly? At least if is_wp_error() was returned you could print out the message.

Thanks.

P.S. Here is the code that adds the article. Note: I’m also not sure why AdminNotice::displayError doesn’t do anything (that’s why I added log output). Am I supposed to put some type of tag on the page (it’s my first ever plugin for a single task)? I got that bit of code from How to add an admin notice upon post save/update

       /**         * Adds a knowledge base article and assign tags and category         * @param $  title The title of the article         * @param $  content The content of the article         * @param $  category The category of the article         * @param $  tags An array of tags to assign to the article         */         function add_ht_kb_article($  title, $  content, $  category, $  tags = array() )         {              $  content=trim($  content);             if( !empty ( $  content ) ){                 $  new_article = array(                       'post_content'   => wp_filter_post_kses($  content),                       'post_title'     => $  title,                       'post_status'    => 'publish',                       'post_type'      => 'ht_kb'                     );                  $  new_article_id = wp_insert_post($  new_article);                  if (is_wp_error($  new_article_id)) {                     $  this->log("Failed (wp_error) to add article {$  title}");                     $  this->log($  new_article_id->get_error_message());                     //return false;                 }                 else if( $  new_article_id != 0 ){                     //ht_kb_categories                     $  res=wp_set_object_terms( $  new_article_id, intval($  category), 'ht_kb_category', true );                     if (is_wp_error($  res)) {                         $  this->log("Failed to add category ID {$  category}");                         AdminNotice::displayError("Failed to add category ID {$  category}");                         return false;                     }                                           //ht_kb_tags                     foreach ($  tags as $  key => $  tag) {                         $  tag_slug = sanitize_title($  tag);                         $  res=wp_set_object_terms( $  new_article_id, $  tag_slug, 'ht_kb_tag', true );                         if (is_wp_error($  res)) {                             $  this->log("Failed to add key tag {$  tag_slug}");                             AdminNotice::displayError("Failed to add key tag {$  tag_slug}");                             return false;                         }                     }                 }                 else {                     $  this->log("Failed (zero) to add article {$  title}");                     AdminNotice::displayError("Failed to add article {$  title}");                     //return false;                 }             }             return true;         } 

wp_insert_post when looping through large file

I seem to be getting an issue with wp_insert_post performing really slow when looping through a large array (130k rows).

I’ve tried a few different tricks speed up the upload such as settings wp_defer_term_counting and wp_defer_comment_counting to true before the bulk insert.

Here is what i have tried:

/**  * Importer class.  */ class Product_Importer {   public $  parsed_csv_data;  public $  csvFile; public $  post_author; public $  post_status; public $  post_type; public $  comment_status; public $  ping_status; public $  publish_date; public $  menu_order;   /**  * Constructor  */ public function __construct($  file = '') {      /* Initialize csv file handle */     $  this->csvFile = $  file;      // Initialise default post data     $  this->publish_date = date("Y-m-d H:i:s");     $  this->post_author = '1';     $  this->post_status = 'published';     $  this->post_type = 'product';     $  this->comment_status = 'closed';     $  this->ping_status = 'closed';     $  this->publish_date;     $  this->menu_order = 1;     $  this->parsed_csv_data = array();  }   /**  * Convert CSV file to an associative array  */ public function parse_csv_to_array() {      // Initialize empty array      $  array = $  fields = array();       $  interval = 0;      // File Handle     $  handle = @fopen($  this->csvFile, "r");      if ($  handle) {          while (($  row = fgetcsv($  handle, 4096)) !== false) {              if (empty($  fields)) {                 $  fields = $  row;                 continue;             }              foreach ($  row as $  k=>$  value) {                 $  array[$  interval][$  fields[$  k]] = $  value;             }              $  interval++;         }          if (!feof($  handle)) {             echo "Error: unexpected fgets() fail\n";         }          fclose($  handle);     }      $  this->parsed_csv_data = $  array;      return $  this->parsed_csv_data; }  /**  * Insert/Replace Products  */ public function upload_product_data() {      // WordPress Database Interface     global $  wpdb;      // Keeps track of product titles so we can rotate the titles     $  unique_products = array();      // Keeps track of current product index/iteration     $  counter = 0;      if (!empty($  this->parsed_csv_data)) {          wp_defer_term_counting( true );         wp_defer_comment_counting( true );          foreach ($  this->parsed_csv_data as &$  product) {              // Initialize product data             $  sku = $  prod_title = $  rrp = $  discount = $  net = null;              // Bind data from array to its own variable             $  sku                    = $  product['PART'];             $  prod_title_with_sku    = $  sku . " | " . $  product['DESCRIPTION'];             $  prod_title             = $  product['DESCRIPTION'];             $  rrp                    = $  product['RRP'];             $  min_order_amount       = $  product['MIN'];             $  discount               = $  product['DISCOUNT'];             $  net                    = $  product['NET'];             $  superceded             = $  product['SUPERCEDED'];              // Increment product name suffix if already exists to prevent duplicate product names             if (in_array($  prod_title, $  unique_products)) {                 $  unique_products[$  prod_title]['count'] += 1;                 $  product['DESCRIPTION'] .= $  unique_products[$  prod_title]['count'];                 $  prod_title = $  product['DESCRIPTION'];             } else {                 $  unique_products[$  prod_title]['count'] = 0;             }              // Append product to array to keep track of duplicate titles so we can increment the count array             $  unique_products[] = $  prod_title;              // Replace spaces with hyphens to allow for wordpress product permalinks             $  formatted_name = str_replace(" ", "-", strtolower($  prod_title));              // Shown in the products description             $  formatted_discount = "Discount Code: " . $  discount;              // Show superceded appended to RRP if field is present             if (empty($  superceded)) {                 $  formatted_rrp = "RRP: " . $  rrp;             } else {                 $  formatted_rrp = "RRP: " . $  rrp . " | SUPERCEDED: " . $  superceded;             }              // Get the post_id from its sku to determine if we should update or insert             $  post_id = $  this->get_post_id_by_sku($  wpdb, $  sku);              // Post data to be inserted/updated             $  post_data = array(                 'ID'                => $  post_id,                 'post_author'       => $  this->post_author,                 'post_date'         => $  this->publish_date,                 'post_date_gmt'     => $  this->publish_date,                 'post_content'      => $  formatted_discount,                 'post_title'        => $  prod_title_with_sku,                 'post_excerpt'      => $  formatted_rrp,                 'post_status'       => $  this->post_status,                 'comment_status'    => $  this->comment_status,                 'ping_status'       => $  this->ping_status,                 'post_name'         => $  formatted_name,                 'post_modified'     => $  this->publish_date,                 'post_modified_gmt' => $  this->publish_date,                 'post_type'         => $  this->post_type,                 'menu_order'        => $  this->menu_order,                 'meta_input'        => array(                                         '_sku' => $  sku,                                         '_regular_price' => $  net,                                         '_price' => $  net,                                         'minimum_allowed_quantity' => $  min_order_amount,                                         'group_of_quantity' => $  min_order_amount                                     )             );              // Insert / Update the post             wp_insert_post( $  post_data );               // Write to file periodically             if ( ($  counter % 25) === 0) {                  // Open/create Progress File                 $  progress_file = fopen(MAN_PLUGIN_PATH . '/uploads/progress.txt', "w") or die("Unable to open file!");                  // Progress File text                 $  status_text = $  counter . '/' . count($  this->parsed_csv_data) . ' Products Uploaded.';                  // Write to progress file with the current iteration                 fwrite($  progress_file, $  status_text);                  // Close file pointer                 fclose($  progress_file);              }              // Increment product index counter             $  counter++;          }          wp_defer_term_counting( false );         wp_defer_comment_counting( false );       // CSV is empty or is not valid     } else {         echo "CSV is empty or isn't valid.";     }      // We can now delete the progress file as the upload process has finished     unlink(MAN_PLUGIN_PATH . '/uploads/progress.txt') or die("Unable to delete file!");  }  /* * Get meta_id by its post_id and key */ public function get_post_id_by_sku($  wpdb, $  sku) {      $  post_id = $  wpdb->get_var( "SELECT post_id FROM " . ($  wpdb->prefix . 'postmeta') . " WHERE `meta_key` = '_sku' AND `meta_value` = '" . $  sku . "';");      // Returning 0 is for wp_insert_post to indicate a new product      if (empty($  post_id)) {         return 0;     }      return $  post_id;  } 

}

When looking at the wp_insert_post function in the source it does look quite complex… but even so, i can’t understand why it is so slow? i am getting around 500 records per minute which i don’t think is great.

I do read to a file every 25 iterations which is then read via ajax as a progress loader but this isn’t intensive or causing the slow insert issue.

wp_insert_post with ACF Fields and WP Meta Query returns no rows until update

I’ve been reading a lot how you can’t use wp_insert_post and update_field because the field isn’t created yet or sum such, so I’ve experimented with MANY permutations of wp_insert_post.

My field is a User object and I’m inserting the User ID. I have multiple values turned on so I update with an array of User IDs with an array of just one entry. There will be multiple entries in the array in the future.

Here’s what I’ve tried:

wp_insert_post and then update_field with just the field name wp_insert_post and then update_field with the field key wp_insert_post and using update_post_meta with just the field name wp_insert_post and using update_post_meta to insert the field name and field key with the underscore version of the field name wp_insert_post and using add_post_meta with the field name and the field key with the underscore version of the field name wp_insert_post with the meta_input in the arguments with both the field name and the field key with the underscore version of the field name

Here’s what happens: The field gets inserted. You can see it in the WP post editor that it was successfully created the right way. Going to the database using PHPMyAdmin reveals that is was added.

Now the weirdness: I’m running THIS query to find out what I need. The query runs on a polling process every 15 seconds to find a new message for user X.

$  args = array(   ‘numberposts’ => -1,   ‘post_status’ => ‘publish’,   ‘post_type’   => ‘message’,   ‘meta_query’ => array(   ‘relation’ => ‘AND’,     array(       ‘key’ => ‘message_recipients’,       ‘value’ => get_current_user_id(),       ‘compare’ => ‘LIKE’     ),     array(       ‘key’ => ‘message_read_by’,       ‘value’ => get_current_user_id(),       ‘compare’ => ‘NOT LIKE’     )   ) ); 

What happens is that the query doesn’t return ANY rows. BUT, when you go into the WP post editor and manually UPDATE the post, THEN and ONLY THEN does the record get found.

I’ve actually tried pulling out the SQL that gets generated from this request and it behaves THE SAME WAY. No rows found until you click UPDATE.

After the record is found, the cleanup happens when my code again runs update_post_meta to insert the user id in the “message_read_by” field, which effectively removes it from the query results because it then doesn’t fit into the second search parameter. So that time IT WORKS. If you don’t touch the data with the WP post editor then it works? This doesn’t make sense.

I need this to work with programmatic inserts without the WP post editor. The data looks the same! Here’s the database view:

The initial programmatic update with the insert. https://imgur.com/BN9DvGi

After I click “update” on the post: https://imgur.com/GnwIgoF

It’s the same data! So why does the query only work after I click update?

The wp_posts table is also the same, except the author user id changes from 3 to 0. I’ve also tried updating that field in the database, but that wasn’t it either.

Is there another field or something that gets changed or updated when I click the UPDATE button in the WP post editor? That’s all I can think of.