Insert A Post With Custom Fields

To insert a custom post from WordPress without using it’s native post page you can use WordPress’ wp_insert_post() function from a plugin or an individual page. In WordPress wp_insert_post() is being used to insert a post programmatically but what if you want to add some custom fields with the post that you are going to insert using wp_insert_post() function. Well, I found this topic very useful during one of my projects and would like to share it. At first you have to insert the post then you can add custom fields.

How to use wp_insert_post function

Above code snippet will just insert a new post into the WordPress database and will return an integer value of the newly inserted post on success, otherwise it will return 0. Please remember that you can specify other values in the $my_post array like post_date, post_status etc but you can omit those because by default those will be inserted. Now we have just inserted a new post and we have the ID of that post. Hence, to insert or add some custom fields with this post we need to add some meta values using add_post_meta() function. This function will insert meta values into the wp_postmeta table using the post’s ID. To add custom field two custom fields we need to call use add_post_meta() function right after wp_insert_post() function and we need the ID ($newpost_id) that wp_insert_post() function returned on success.

How to use add_post_meta function

Above code snippet will add two custom fields with the new post. The add_post_meta() function accepts three arguments, first on is the post ID, for which the meta value will be added, the second on is the custom field name (meta_key name) and third one is the field value (meta_value). Here we have added two custom fields profession and status, that’s it.

To update a post and it’s custom fields (meta values) you need to use wp_update_post function and update_post_meta function.

You can learn more about it from codex.wordpress.org

Latest Blog