Search code examples
wordpresspluginsposts

Plugin Development - wp insert post not working


I am new to plugin development for WP. I have a problem with wp_insert_post from the plugin file, tested running this plugin php file, and all the code before the wp_insert_post is fine, but once it jumps on wp_insert_post nothing happens after, stuck at 'Test15'. Tested running the insert post part of the code from test page within the theme folder and it worked. Not sure what is the problem here. Please see the code below.

function db_importer_insert_properties($properties, $category, $user_id, $post_type) {

echo 'Test9<br>'; 
$result = true;
echo 'Test10<br>'; 
if($properties) {
      echo 'Test11<br>';
if(count($properties) > 0) {
      echo 'Test12<br/>';
      print_r($properties);
      echo '<br/>';
  $count = 0;
  foreach($properties as $property) {
    echo 'Test13<br/>';

    $address =$property['address'] ; //get title

    $building=$address['streetNumber'];
    $street=$address['street'];
    $suburb=$address['suburb'];
    $state=$address['state'];
    $postcode=$address['postcode'];

    $title=$building. ' ' .$street.', '.$suburb.', '.$postcode.', '.strtoupper($state);

    //test post
    $new_post = array(
      'post_title'    => 'My post10 ',
      'post_content'  => 'This is my post10 ',
      'post_status'   => 'publish',
      'post_author'   => 1,
      'post_category' => 'uncategorized'
  );
    echo 'Test14<br/>';
    print_r($new_post);
    echo '<br/>';
    echo 'Test15<br/>';


    wp_insert_post($new_post);
    echo 'Test16<br>';

  if($post_id != 0) {

    add_post_meta($post_id, "_bathrooms", esc_attr($property['features']['bathrooms']));
    add_post_meta($post_id, "_bedrooms", esc_attr($property['features']['bedrooms']));

    if(is_array($property['images'])) {
      add_post_meta($post_id, "_images", esc_attr(implode("\n", $property['images']))); 
    }
    else {
     feedback("Post ID was 0");
    }   

    feedback("added property $title with post_id $post_id"); 
    $count++; 
  }
  else {
    feedback("post was failed to add");
  }
}
feedback("Added $count properties");

}
else {
  feedback("No properties to add.");
 }
}
else {
  feedback("No properties were selected");
  $result = false;
}
  return $result;

}


Solution

  • You forgot to declare your $post_id variable. Use the following:

    $post_id = wp_insert_post( $new_post, true );
    

    This will return the post ID on success or a WP error on failure.

    Use print_r( $post_id ) to check the result.