Codex tools: Log in
Languages: English • Русский • (Add your language)
Contents |
Эта функция создает записи (и страницы) в базе данных. Она очищает переменные, делает некоторые проверки, заполняет недостающие переменные, такие как дата/время, и тп. Она берет объект в качестве аргумента и возвращает значение post ID созданной записи (или 0 если обнаружены ошибки).
ВАЖНО: Установленное значение для $post['ID'] НЕ БУДЕТ создавать запись с этим ID номером. Установка этого значения вызовет функцию для обновления записи с этим ID номером с другими значениями, указанными в $post. Короче говоря, чтобы создать новую запись, параметр $post['ID'] должен быть пустым или вообще не установлен.
Содержание массива записи может зависеть от того, как много (или мало) параметров вы хотите оставить по умолчанию. Вот список с кратким описанием всех ключей, которые можно установить для записи:
$post = array( 'ID' => [ <post id> ] //Are you updating an existing post? 'menu_order' => [ <order> ] //If new post is a page, sets the order should it appear in the tabs. 'comment_status' => [ 'closed' | 'open' ] // 'closed' means no comments. 'ping_status' => [ 'closed' | 'open' ] // 'closed' means pingbacks or trackbacks turned off 'pinged' => [ ? ] //? 'post_author' => [ <user ID> ] //The user ID number of the author. 'post_category' => [ array(<category id>, <...>) ] //Add some categories. 'post_content' => [ <the text of the post> ] //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' => [ <an excerpt> ] //For all your post excerpt needs. 'post_name' => [ <the name> ] // The name (slug) for your post 'post_parent' => [ <post ID> ] //Sets the parent of the new post. 'post_password' => [ ? ] //password for post? 'post_status' => [ 'draft' | 'publish' | 'pending'| 'future' | 'private' ] //Set the status of the new post. 'post_title' => [ <the title> ] //The title of your post. 'post_type' => [ 'post' | 'page' | 'link' | 'nav_menu_item' | custom post type ] //You may want to insert a regular post, page, link, a menu item or some custom post type 'tags_input' => [ '<tag>, <tag>, <...>' ] //For tags. 'to_ping' => [ ? ] //? 'tax_input' => [ array( 'taxonomy_name' => array( 'term', 'term2', 'term3' ) ) ] // support for custom taxonomies. );
Примечание: Ключ page_template был удален из таблицы параметра $post и теперь находится в таблице wp_postmeta. Чтобы настроить шаблон записи, используйте функцию update_post_meta совместно с ключом _wp_page_template.
Примечание 2: Ключ post_status описан в Post Status Transitions.
Примечание 3: Если вы указываете post_status со значением 'future', то вы должны указать post_date для того чтобы WordPress знал когда опубликовывать вашу запись.
The ID of the post if the post is successfully added to the database. On failure, it returns 0 if $wp_error is set to false, or a WP_Error object if $wp_error is set to true.
<?php wp_insert_post( $post, $wp_error ); ?>
Before calling wp_insert_post() it is necessary to create an array to pass the necessary elements that make up a post. The wp_insert_post() will fill out a default list of these but the user is required to provide the title and content otherwise the database write will fail.
The user can provide more elements than are listed here by simply defining new keys in the database. The keys should match the names of the columns in the wp_posts table in the database.
// Create post object
$my_post = array(
'post_title' => 'My post',
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(8,39)
);
// Insert the post into the database
wp_insert_post( $my_post );
The default list referred to above is defined in the function body. It is as follows:
$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' => '',
'import_id' => 0);
Categories need to be passed as an array of integers that match the category IDs in the database. This is the case even where only one category is assigned to the post.
See also: wp_set_post_terms()
wp_insert_post() passes data through sanitize_post(), which itself handles all necessary sanitization and validation (kses, etc.).
As such, you don't need to worry about that.
wp_insert_post() is located in wp-includes/post.php.
wp_update_post(), wp_delete_post(), wp_publish_post(), wp_delete_attachment(), wp_get_attachment_url(), wp_insert_attachment(), wp_insert_post_data()