wp_insert_post() │ WP 1.0.0
Безопасно вставляет/обновляет запись в базе данных.
Функция очищает передаваемые данные; делает некоторые проверки; заполняет пропущенные переменные (например, если не передать дату поста, то дата будет получена автоматически).
Ожидает экранированные данные. Это значит, если в функцию передаются не POST данные, то перед отправкой нужно обработать массив данных функцией wp_slash()
ВАЖНО! Указать ‘post_author’ => user_id , если код вызывается не из под юзера, например, через CRON, REST и т.д. По умолчанию туда вставляется ИД текущего пользователя, и если текущего юзера нет, то получим 0 и кучу багов.
Имейте ввиду, в функции срабатывают разные хуки, например save_post, wp_insert_post. В колбэках этих хуков могут быть использованы $_POST/$_GET данные, но они могут отсутствовать во фронте. Поэтому могут быть ошибки, когда функция используется во фронте — ищите ошибки в функциях хуков.
Что конкретно понимается под записями, читайте в этой статье: Записи в WordPress
Категории
Категории нужно передавать в виде массива чисел, совпадающих с ID категорий в базе данных. Это относится и к случаю, когда передается одна категория.
Безопасность (очистка заголовка поста)
Функция обрабатывает переданные данные с помощью функции sanitize_post() — она проверяет и очищает значения всех полей. Поэтому можно не беспокоится об очистке передаваемых данных.
Однако, возможно вам нужно будет удалить HTML теги и другие нестандартные символы из заголовка записи. WordPress не делает это автоматически для заголовка. Это можно сделать использовав sanitize_text_field(), особенно это актуально, когда посты можно публиковать с фронт-энда:
emoji заметка
C версии 4.2, с введением смайликов эмодзи. Функция автоматически конвертирует символы-смайликов в полях ‘post_title’, ‘post_content’, ‘post_excerpt’, если кодировка таблицы utf8, а не utf8mb4. К этим полям применяется функция wp_encode_emoji().
Developer Resources
Inserts or update a post.
Contents
Description
If the $postarr parameter has ‘ID’ set to a value, then post will be updated.
You can set the post date manually, by setting the values for ‘post_date’ and ‘post_date_gmt’ keys. You can close the comments or open the comments by setting the value for ‘comment_status’ key.
See also
Parameters
$fire_after_hooks bool Optional
Return
int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
More Information
Usage
Notes
- post_title and post_content are required
- post_status: If providing a post_status of ‘future’ you must specify the post_date in order for WordPress to know when to publish your post. See also Post Status Transitions.
- post_category: Equivalent to calling wp_set_post_categories().
- tags_input: Equivalent to calling wp_set_post_tags().
- tax_input: Equivalent to calling wp_set_post_terms() for each custom taxonomy in the array. If the current user doesn’t have the capability to work with a taxonomy, then you must use wp_set_object_terms() instead.
- page_template: If post_type is ‘page’, will attempt to set the page template. On failure, the function will return either a WP_Error or 0, and stop before the final actions are called. If the post_type is not ‘page’, the parameter is ignored. You can set the page template for a non-page by calling update_post_meta() with a key of ‘_wp_page_template’.
Categories
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.
Security
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.
Source
Hooks
Fires once an attachment has been added.
Filters whether or not to add a __trashed suffix to trashed posts that match the name of the updated post.
Fires once an existing attachment has been updated.
Fires once an existing attachment has been updated.
Fires once an existing post has been updated.
Fires once an existing post has been updated.
Fires once an existing post has been updated.
Fires immediately before an existing post is updated in the database.
Fires once a post has been saved.
Fires once a post has been saved.
Filters attachment post data before it is updated in or added to the database.
Fires once a post has been saved.
Filters slashed post data just before it is inserted into the database.
Filters whether the post should be considered “empty”.
Filters the post parent — used to check for and prevent hierarchy loops.
Related
Uses | Description | ||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wp_resolve_post_date() wp-includes/post.php |
Used By | Description | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
WP_Theme_JSON_Resolver::get_user_data_from_wp_global_styles() wp-includes/class-wp-theme-json-resolver.php | ||||||||||||
WP_REST_Templates_Controller::update_item() wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | ||||||||||||
WP_REST_Templates_Controller::create_item() wp-includes/rest-api/endpoints/class-wp-rest-templates-controller.php | ||||||||||||
WP_Customize_Manager::save_changeset_post() wp-includes/class-wp-customize-manager.php | ||||||||||||
WP_REST_Posts_Controller::create_item() wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php | ||||||||||||
WP_Customize_Nav_Menus::insert_auto_draft_post() wp-includes/class-wp-customize-nav-menus.php | ||||||||||||
wp_xmlrpc_server::blogger_newPost() wp-includes/class-wp-xmlrpc-server.php | ||||||||||||
wp_xmlrpc_server::mw_newPost() wp-includes/class-wp-xmlrpc-server.php | ||||||||||||
wp_xmlrpc_server::_insert_post() wp-includes/class-wp-xmlrpc-server.php |
Version | Description |
---|---|
5.6.0 | Added the $fire_after_hooks parameter. |
4.4.0 | A ‘meta_input’ array can now be passed to $postarr to add post meta data. |
4.2.0 | Support was added for encoding emoji in the post title, content, and excerpt. |
2.6.0 | Added the $wp_error parameter to allow a WP_Error to be returned on failure. |
1.0.0 | Introduced. |
User Contributed Notes
Insert post with custom taxonomy and post meta data (since 4.4.0):
‘tax_input’ in the arguments only works on wp_insert_post if the function is being called by a user with “assign_terms” access
Inserting a Post
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 next example shows the post title, content, status, author, and post categories being set. You can add further key-value pairs, making sure the keys match the names of the columns in the wp_posts table in the database.
You can also get the new post ID after inserting a new post:
As @Kiera Howe brilliantly noticed, ‘tax_input’ requires ‘assign_terms’ access.
Depending on the case it can make its use impracticable.
A quick solution could be replacing it by:
Feedback
Another solution could be to use wp_set_current_user( 1 ); beforehand, assuming the ID ‘1’ is the super admin. — By rinopo — 3 years ago
Its important that you validate your post ID before you use by checking if the returned values is not a WP_error,
Feedback
Variables must be escaped when echo’d. Line 10 should read: echo esc_html( $post_id->get_error_message() ); — By wpexplorer — 1 year ago
The post_template parameter should be described as well.
It should be set with a full file name, such as ‘templatefilename.php’.
This clarify will help developers trying to tie a template to a page.
Feedback
And make sure to also add the subdirectory if your template is not in the theme’s root folder. So for example ‘page_template’ => ‘templates/tpl_default.php’ — By Larzans — 3 years ago
By default, wp_insert_post will not insert an empty post. This can cause unexpected problems if you’re passing an ID and expecting it to fall back to wp_update_post . For instance, the following will not work:
You will need to call wp_update_post directly.
When saving data containing slashes remember to add extra slashes due to wp_insert_post unslashing these values.
Will store (b16-d<3>b) . To fix this use wp_slash() :
The format for post_date and post_date_gmt input is Y-m-d H:i:s , for instance 2019-01-01 01:01:01 . You can use PHP’s date function, like this:
About taxonomy parameter
Parameters: ‘tax_input’ (array) Array of taxonomy terms keyed by their taxonomy name. Default empty.
The description for the parameter ‘tax_input’ is not clearly stated and no example is given so far, so I would like to add a supplementary note here for the exact meaning and examples.
According to the source code of ‘wp_insert_post()’, the ‘tax_input’ is being added by function ‘wp_set_post_terms()’. So I refer to its description that Here is the example for using this:
- $taxomony – (string) Taxonomy name $tags – (string|array) An array of terms to set for the post, or a string of terms separated by commas. (tags)
eg.
Tested: I have personally tested it in a custom post type with custom category(taxonomy) name with wp_update_post()
To add Taxonomy and Meta field values with custom post types.
For Taxonomy:
Make sure Taxonomy name is key of tax_input array. And the array of Taxonomy ID’s is value of that key like in example below.
For Meta Values:
You can pass meta value name as key and meta value as that keys value.
If you’re creating a post and the post ID doesn’t yet exist, using ‘ID’ => your_number will not create a new post. It will return blank, because it searched for the ID and it didn’t exist.
Instead, use ‘import_id’ like this:
Prevent duplicate post
Directly insert existing attachment with id 32 to post thumbnail.
Create a post for custom post type :
Watch out when updating a post using wp_insert_post(); if you don’t explicitly specify the post_status, it will change it back to ‘draft’.
I ended up using wp_update_post() instead.
To work with this function, you should add condition to each of
The second thing, in case you push multiple params like multiple checkbox checked, you should know how to push to array:
The example markup:
We should check and using this function to keep it working:
This snippet creates a post with code checking if the post already exists before creating it.
You must log in before being able to contribute a note or feedback.
Adblockdetector