【问题标题】:Plugin Development - wp insert post not working插件开发 - wp插入帖子不起作用
【发布时间】:2015-01-10 00:33:42
【问题描述】:

我是 WP 插件开发的新手。我对插件文件中的 wp_insert_post 有问题,测试了运行这个插件 php 文件,并且 wp_insert_post 之前的所有代码都很好,但是一旦它跳转到 wp_insert_post 之后什么都没有发生,卡在“Test15”。测试从主题文件夹中的测试页面运行代码的插入帖子部分并且它有效。不知道这里有什么问题。请看下面的代码。

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;

}

【问题讨论】:

    标签: wordpress plugins posts


    【解决方案1】:

    您忘记声明 $post_id 变量。使用以下内容:

    $post_id = wp_insert_post( $new_post, true );
    

    这将在成功时返回帖子 ID 或在失败时返回 WP 错误。

    使用print_r( $post_id )查看结果。

    【讨论】:

    • 感谢 Diggy,但由于某种原因它不起作用...有没有办法检查 wp_insert_post 背后发生了什么?
    • 如果失败,它应该返回一个 WP 错误对象。我注意到post_category 需要一组猫 ID,但我认为这不会导致重大问题。包含您的代码的文件是否可以访问 WP 功能?
    • 我怎么错过了???哈哈,谢谢 mate___))) 我忘了包括 /wp-load.php....傻了我...再次感谢,我在过去的两个小时里一直在挣扎
    猜你喜欢
    • 2015-09-26
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多