使用MySql在Wordpress中插入帖子

Uff*_*ffo 17 mysql wordpress wordpress-plugin

有谁知道如何使用sql将新帖子插入Wordpress?

Chu*_*way 31

您可以使用Post对象:

// Create post object
  $my_post = array();
  $my_post['post_title'] = 'My post';
  $my_post['post_content'] = 'This is my post.';
  $my_post['post_status'] = 'publish';
  $my_post['post_author'] = 1;
  $my_post['post_category'] = array(8,39);

// Insert the post into the database
  wp_insert_post( $my_post );
Run Code Online (Sandbox Code Playgroud)

更多信息在这里找到.

  • 顺便说一下,如果你想测试一下,在博客的根目录下创建一个"test.php"文件,并在此代码之前使用这一行:require('./ wp-blog-header.php'); (6认同)
  • 该类别必须是类别ID的数组.这并不容易,特别是如果你没有与类别相关的帖子.类别赋值的修正是这样的:$ sCategory ='Test'; $ asPost ['post_category'] = array($ wpdb-> get_var("SELECT term_id FROM $ wpdb-> terms WHERE name ='$ sCategory'", 0,0)); (2认同)

phi*_*reo 14

您的问题询问如何使用SQL将新帖子插入WordPress.如果你真的想这样做,看看"wp"数据库​​表并做一个标准的INSERT - 这并不难.

但我强烈建议不要这样做 - 即使你想在普通的WP提供的之外创建一个单独的管理仪表板,你应该使用他们提供的核心功能/API.例如,wp_insert_post函数就是您要使用的函数.

我相信你可以通过包含/wp-load.php来使用/加载这些功能.

  • 我对Wordpress有些新手,我想知道为什么你建议不要使用基本的SQL插件? (3认同)
  • @ssergei,因为Wordpress为您提供了API。 (2认同)

小智 6

我开始导出"wp_post"表只是为了查看结构 - 然后复制第一部分并编写了第二部分;

1:从可用于insert语句的变量开始($ sql)

$sql = "INSERT INTO `wp_posts` (`ID`, `post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`) VALUES ";
Run Code Online (Sandbox Code Playgroud)

2:我从另一个表中获取了我想要插入的内容 - 但是你可以在语句的内部或外部设置变量,只需将变量设置为你想要的 -

$sql .= "(' ','".$post_author."',"."'".$post_date."',"."'".$post_date_gmt."',"."'".$post_content."',"."'".$post_title."',"."'".$post_excerpt."',"."'".$post_status."',"."'".$comment_status."',"."'".$ping_status."',"."'".$posd_password."',"."'".$post_name."',"."'".$to_ping."',"."'".$pinged."',"."'".$post_modified."',"."'".$post_modified_gmt."',"."'".$post_content_filtered."',"."'".$post_parent."',"."'".$guid."',"."'".$menu_order."',"."'".$post_type."',"."'".$post_mime_type."',"."'".$comment_count."'),";
Run Code Online (Sandbox Code Playgroud)

之后,使用您的标准查询:

$res = mysql_query($sql); if($res): print 'Successful Insert'; else: print 'Unable to update table'; endif;
Run Code Online (Sandbox Code Playgroud)

  • 它不起作用,因为没有为帖子分配类别,因此它将无法正确显示... (2认同)