create a new post with wordpress

How to create posts and pages programmatically

WordPress features allow you to add posts and pages easily with editor on your website. Do you know that it is also very simple if you want to make it programmatically for your custom theme or plugin?

You can add posts, pages, and custom post types with only one function and a few parameters. Nothing more is required. Let’s see this code together.

Create a post with wp_insert_post function

The function to use is wp_insert_post(), you can find the complete documentation here.

There is another way to create posts programmatically with SQL (with $wpdb->prepare & $wpdb->query), but we don’t recommend this method since wp_insert_post should cover all your needs.

Parameters and example are explained below.

Parameters wp_insert_post explained

Example of a simple new post added programmatically:

$post_id = wp_insert_post( 
			'post_content'          => 'My content here', 
			'post_category'         => array( 1, 2 ), 
			'post_title'            => 'My title here', 
			'post_status'           => 'publish',
			'post_author'           => 1

You can see that only five parameters (and even less) can do the job!

In this example above, the variable $post_id will return the new post ID, or false if the post cannot be created.

Let’s see every import parameter:

  • ID: If you want to create a new post, do not include this parameter, it will be generate automatically. If you provide an existing ID of a post, this post will be updated with the new content provided
  • post_author: The author ID. If you do not provide this parameter, the post will not be assign to any WordPress author.
  • post_date: If you don’t provide this parameter, it will be the current date. If you want another date you should put something in this format date( 'Y-m-d H:i:s', time() )
  • post_content: the post content
  • post_title: the post title
  • post_excerpt: the post excerpt
  • post_type: your post type . Default will be “post”, you can also set “page” or your custom post type
  • post_category: Your categories ids into an array
  • tags_input: Your tags ids into an array. You can also put tag names or slugs
  • post_status: Your post status. For example, publish (default), draft or future
  • post_parent: ID post parent if provided

If you need more options, you should read the description here.

Where to put this code ?

Usages of WordPress suggest adding your custom features into a new custom plugin (and not into the theme).

If you add your code into your theme functions.php file, it will work without any problem if this is not the most recommended.

You can also use a hook to insert a new post, most hooks are listed here.

Still stuck ? You can contact an expert.

Leave a Comment

Your email address will not be published.

You may also like