WordPress插入文章到数据库,常用函数-wp_insert_post()
网络科技
0
常用函数-wp_insert_post()
说明
该函数可在数据库中插入文章(及页面)。它可以进行处理变量,检查操作,填充日期/时间等缺失变量等工作。该函数以对象作为变量,返回已创建文章的编号(出错时返回0)。用法
示例
调用wp_insert_post()前需创建对象以传递组成文章的必要元素。wp_insert_post()可自动填写默认表格,但用户需提供文章标题和内容,否则数据库写入不成功。 用户可在数据库中简单定义新关键字,之后就可以添加更多文章要素。关键字应与数据库wp_posts表格中纵列名称相匹配。// 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 );上面提到的默认表格在函数主体中有所定义。定义如下:
$defaults = array( 'post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '' );
类别
需要将类别作为整数数组传递,该数组应与数据库中的类别编号相匹配。即使文章只属于某一项类别,情况也应如此。参数
$post (对象)(必需)能表示可组成文章元素的对象。这些元素与数据库wp_posts表格中的纵列名称应一一对应。 默认值:空 文章数组的内容可取决于用户的默认值的信赖程度。下表列出了用户可为文章设置的所有选项:$post = array( 'comment_status' => [ 'closed' | 'open' ] // 'closed' means no comments. 'ID' => [] //Are you updating an existing post? 'menu_order' => [ ] //If new post is a page, sets the order should it appear in the tabs. 'page_template => [ ] //Sets the template for the page. 'ping_status' => [ ? ] //Ping status? 'pinged' => [ ? ] //? 'post_author' => [ ] //The user ID number of the author. 'post_category => [ array( , <...>) ] //Add some categories. 'post_content' => [ ] //The full text of the post. 'post_date' => [ Y-m-d H:i:s ] //The time post was made. 'post_date_gmt' => [ Y-m-d H:i:s ] //The time post was made, in GMT. 'post_excerpt' => [ ] //For all your post excerpt needs. 'post_parent' => [ ] //Sets the parent of the new post. 'post_password' => [ ? ] //password for post? 'post_status' => [ 'draft' | 'publish' | 'pending' ] //Set the status of the new post. 'post_title' => [ ] //The title of your post. 'post_type' => [ 'post' | 'page' ] //Sometimes you want to post a page. 'tags_input' => [ ' , , <...>' ] //For tags. 'to_ping' => [ ? ] //? );
返回的值
若文章成功加入数据库,返回文章编号。否则返回0. 完整引用代码,放到根目录即可运行。define( 'WP_USE_THEMES', true ); $wp_did_header = true; // Load the WordPress library. // require_once __DIR__ . '/wp-load.php'; if ( ! defined( 'ABSPATH' ) ) { define( 'ABSPATH', __DIR__ . '/' ); } error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR ); if ( file_exists( ABSPATH . 'wp-config.php' ) ) { /** The config file resides in ABSPATH */ require_once ABSPATH . 'wp-config.php'; } // 创建文章对象 $my_post = array( 'post_title' => '我的测试文章', 'post_content' => '这是一个测试文章。', 'post_status' => 'publish', 'post_author' => 1, //对应作者 ID 'post_category' => array(4) //对应文章分类 ); // 插入文章到数据库 wp_insert_post( $my_post );
版权声明:除非特别标注原创,其它均来自互联网,转载时请以链接形式注明文章出处。