Creating a WordPress page using PHP can be a powerful code recipe to have. In this guide we will share code on just how to do that.

This guide will require you to know a bit of PHP to get it working as intended and will cover the basics so that you may implement this in a project you are working on.

A great example would be to create a WordPress post or page when a user is added from Zapier using our WP Zapier plugin. (You are able to hook into anywhere you’d like).

For this guide we will be leveraging the wp_insert_post function.

Show Me The Code

Break Down Of The Code

The wp_insert_post function takes quite a few parameters, but we only need to use a few to get it working. Call this function anywhere to create a post/page or custom post type on any hook you’d want to.

wp_insert_post takes two parameters, an array of data for the post and it’s settings and a boolean value to return an error on post creation or not – we can ignore this for this example.

The $post_data array

The $post_data is an array of values that tells WordPress to add this information to a new post. This includes things such as the post’s Title, the actual content of the post, the author and much more.

Let’s look at the example from above:

  • post_title – This is the title of the post. You may include HTML, JavaScript and PHP. To be safe, you may use the wp_strip_all_tags function.
  • post_content – The actual ‘meat’ of the post. This will be the body of the page/post.
  • post_status – Set this to ‘publish’ to automatically publish the post to your site. If user’s are submitting posts, I’d recommend in keeping it to ‘draft’.
  • post_author – The author of the post. Set this to the user’s ID.
  • post_category – Assign your post to multiple or single categories. In the above example we pass through the category ID’s.
  • post_type – Set this to the type of post this will be: page, post, product or any other custom post type.

This is only a handful of options you can pass through and there is much more. View the WordPress documentation for all available parameters.

Summary

This is just the tip of the iceberg. The wp_insert_post function is very powerful to create a WordPress page or post using PHP. This could be creating pages from form submissions, third part applications and much more. Feel free to leave a comment below if you have any further questions regarding this guide.

Photo by Hayden Scott on Unsplash