Programmatically create WordPress Posts and Pages using PHP.
Quick Summary of Contents
It’s been a while since I last graced you with a tutorial. That said, you guessed right if you guessed today’s post is a tutorial. 🙂
To be exact, this automation tutorial discusses in great detail how to programmatically create WordPress posts and pages using PHP.
I operate a number of WordPress websites where I spend a good bit of time, like 5 to 6 hours daily of repetitive tasks, manually curating and updating content. There has to be a better way right?
Unfortunately, it only took 6 months for me to question and realize that I could automate everything right down to scheduling each WordPress post using PHP.
It wasn’t that I didn’t know, but it was more like would I stop and set aside the time to invest in planning and executing a sound automation strategy. Good ole’ procrastination…
Nevertheless, imagine how freeing and liberating it is to programmatically automate the aforementioned repetitive tasks.
Now, instead of 5-6 hours of daily manual work, I simply upload my files to a web server and use an automated daily cron job to create and schedule WordPress posts.
I’ve gone from hours down to exactly 3 minutes tops of manual labor, and you can do the same too when completing today’s tutorial.
Tutorial Pre-Requisites
Before starting, be sure to have the following pre-requisites met:
- WAMPP, XAMPP, or LAMP Web or local server
- MySQL version(s) 5 or greater
- PHP version(s) 5.3 or greater
- WordPress version(s) 4.7 or greater
- Text editor of your choice – Notepad++, Sublime, and Dreamweaver
In addition, be sure to know which timezone your web or local server is set to. You may have to set it via php.ini, httpd.conf, or another system file containing timezone settings.
The timezone of your web or local server will greatly impact when a post is scheduled and published.
Also, be sure you know how to access the MySQL database via phpMyAdmin, command line interface, or console.
Feel free to also use Lynda.com to research videos and tutorials for any of the listed prerequisites.
Accessing built-in WordPress functions
Within the root directory of your WordPress website directory, create a new folder. The folder I created for this tutorial is the test folder.
Within the text folder, create and save a file named test.php using the text editor of your choice.
You could create the test.php file as a file that lives in the WordPress root directory, but I personally like keeping scripting files in their own PHP folders.
The first step in the test.php file is to require the wp-load.php file which loads and offers access to built-in WordPress functions. Specifically, we’ll use the WordPress function wp_insert_post() to create today’s post.
<?PHP // require wp-load.php to use built-in WordPress functions require_once("../wp-load.php"); ?>
Defining and setting post variables
Next, set the post variables to be passed as an array object to the wp_insert_post() function.
There are quite a few post-variable parameters that wp_insert_post() accepts, but for the sake of this tutorial, use the following:
- postType – set this variable to ‘post’ or ‘page’
- userID – you’ll likely need to access MySQL table for WordPress users to obtain the distinct id of the user you would like the post or page to be published by.
- categoryID – set a single category id (tags also) or a chain of integer ids separated by commas (e.g. ‘2,3,4,5’)
- leadTitle – set this to the desired title
- leadContent – set this to be the HTML string for your post’s content
- review the how-to tutorial set a featured image
<?PHP /******************************************************* ** POST VARIABLES *******************************************************/ $postType = 'post'; // set to post or page $userID = 1; // set to user id $categoryID = '2'; // set to category id. $postStatus = 'future'; // set to future, draft, or publish $leadTitle = 'Exciting new post today: '.date("n/d/Y"); $leadContent = '<h1>Vacations</h1><p>Vacations are the best thing in this life.</p>'; $leadContent .= ' <!--more--> <p>Expensive they are, but they are totally worth it.</p>'; ?>
Defining, setting, and calculating time variables
The next phase of this tutorial can be a bit tricky to understand when you’re attempting to create only a post.
The easy thing to do would be to set the timeStamp variable and not have any calculations whatsoever.
However, I wanted to share with you how you might add a bit more functionality to the script with a bit more elbow grease.
Essentially, you could run this scripting for multiple tasks using a built-in PHP foreach statement that iterates each task.
Doing this allows you to set the iCounter variable to increment by one via each task iteration. Then you could simply set the time increments (i.e., minuteIncrement) multiplied by the iCounter variable for each posting to not post at the same time but to have staggered posting times.
The tricky part of all of this is knowing what timezone your web or local server is set to, and how many minutes (i.e., adjustClockMinutes) should be added for each posting to be posted at the desired time slot.
For the sake of this tutorial, we’re simply scheduling the post to be published one minute into the future via the timeStamp variable’s WordPress-friendly formatted date.
<?PHP /******************************************************* ** TIME VARIABLES / CALCULATIONS *******************************************************/ // VARIABLES $timeStamp = $minuteCounter = 0; // set all timers to 0; $iCounter = 1; // number use to multiply by minute increment; $minuteIncrement = 1; // increment which to increase each post time for future schedule $adjustClockMinutes = 0; // add 1 hour or 60 minutes - daylight savings // CALCULATIONS $minuteCounter = $iCounter * $minuteIncrement; // setting how far out in time to post if future. $minuteCounter = $minuteCounter + $adjustClockMinutes; // adjusting for server timezone $timeStamp = date('Y-m-d H:i:s', strtotime("+$minuteCounter min")); // format needed for WordPress ?>
Create and bind variables, and make insert
We’re almost home free. The final step is to bind all necessary variables (see and read more on wp_insert_post() arguments and default values) into an array (i.e., new_post).
Once the new_post variable array has been created, it can now be passed to the wp_insert_post() function as an argument.
<?PHP /******************************************************* ** WordPress Array and Variables for posting *******************************************************/ $new_post = array( 'post_title' => $leadTitle, 'post_content' => $leadContent, 'post_status' => $postStatus, 'post_date' => $timeStamp, 'post_author' => $userID, 'post_type' => $postType, 'post_category' => array($categoryID) ); ?>
The final step is creating a post_id variable and setting it equal to wp_insert_post(). Upon successful entry of a page or post in WordPress, the wp_insert_post() function returns an id.
Last but not least, we use a simple if else statement to determine whether wp_insert_post() function returns an id. If successful, then post-insertion is executed. If not, then post-insertion execution failed.
We then echo the finaltext variable to the web browser display. That’s it.
<?PHP /******************************************************* ** WordPress Post Function *******************************************************/ $post_id = wp_insert_post($new_post); /******************************************************* ** SIMPLE ERROR CHECKING *******************************************************/ $finaltext = ''; if($post_id){ $finaltext .= 'Yay, I made a new post.<br>'; } else{ $finaltext .= 'Something went wrong and I didn\'t insert a new post.<br>'; } echo $finaltext; ?>
Bring it together and test your code
It’s time to bring each section of code together, save it, and test out your technical prowess.
Now that you can programmatically create WordPress posts and pages using this PHP script, think of all the many things you could do.
Although I didn’t cover it specifically, if you know how to parse files via PHP, then you could create any one of the following:
- A deals website
- A content website
- A jobs website
- and many other affiliate marketing ideas…
If you’re new to affiliate marketing or could simply use some ideas for how to automate affiliate marketing, then I encourage you to read and STUDY the following books:
Good luck with automating your future, and realizing time savings, and let me know if you have any questions whatsoever.
<?PHP // require wp-load.php to use built-in WordPress functions require_once("../wp-load.php"); /******************************************************* ** POST VARIABLES *******************************************************/ $postType = 'post'; // set to post or page $userID = 1; // set to user id $categoryID = '2'; // set to category id. $postStatus = 'future'; // set to future, draft, or publish $leadTitle = 'Exciting new post today: '.date("n/d/Y"); $leadContent = '<h1>Vacations</h1><p>Vacations are the best thing in this life.</p>'; $leadContent .= ' <!--more--> <p>Expensive they are, but they are totally worth it.</p>'; /******************************************************* ** TIME VARIABLES / CALCULATIONS *******************************************************/ // VARIABLES $timeStamp = $minuteCounter = 0; // set all timers to 0; $iCounter = 1; // number use to multiply by minute increment; $minuteIncrement = 1; // increment which to increase each post time for future schedule $adjustClockMinutes = 0; // add 1 hour or 60 minutes - daylight savings // CALCULATIONS $minuteCounter = $iCounter * $minuteIncrement; // setting how far out in time to post if future. $minuteCounter = $minuteCounter + $adjustClockMinutes; // adjusting for server timezone $timeStamp = date('Y-m-d H:i:s', strtotime("+$minuteCounter min")); // format needed for WordPress /******************************************************* ** WordPress Array and Variables for posting *******************************************************/ $new_post = array( 'post_title' => $leadTitle, 'post_content' => $leadContent, 'post_status' => $postStatus, 'post_date' => $timeStamp, 'post_author' => $userID, 'post_type' => $postType, 'post_category' => array($categoryID) ); /******************************************************* ** WordPress Post Function *******************************************************/ $post_id = wp_insert_post($new_post); /******************************************************* ** SIMPLE ERROR CHECKING *******************************************************/ $finaltext = ''; if($post_id){ $finaltext .= 'Yay, I made a new post.<br>'; } else{ $finaltext .= 'Something went wrong and I didn\'t insert a new post.<br>'; } echo $finaltext; ?>
Watch the tutorial video for more in-depth details
And for those of you that love watching video tutorials, I created a video too. Enjoy! 😉
Hey this is a very helpful post! Do you know how to add tags to the post programmatically? Either way, thanks for this. It will save me alot of time.
Have you tried wp_set_post_tags?
No but I did find it after googling. I’ll give it a try when it’s time. Thanks for the quick reply. 🙂
Hi TJ, I also released a video this week about setting and updating tags to WordPress Posts. Let me know if you run into any issues.
Hi Alvin,
Very informative but I have one question. This only runs when you hit the file correct? How would I schedule this so it happens every 15min?
Hi Mike – Correct, the file executes only when loaded in the web browser. If you’re in search of automating the execution of the file “every x min”, then you’ll likely need to investigate cron jobs. What type of environment is your php file hosted in (i.e., Linux, Windows, etc.)?
Hi Alvin,
Thanks for your post
this post helped me a lot!
currently i can successfully post a post,
but now wondering how can i add a “featured image” to an auto posted post,
do you know which function or where i should look at?
the webpage i entered was the page i apply auto update function… 🙂
Thanks!
Hi Tim – Sorry it took some time, but got around to making a step-by-step tutorial and tutorial video showing how to automate “feature image” post. Enjoy and let me know if you have questions.
Hi Alvin,
Thanks a lot for posting this. The only problem I have is I don´t host the WordPress files in my computer. How can I manually add the new php code in the WordPress dashboard?
Thank you 🙂
Do you have access to the root directory hosting WordPress?
Thank you ALvin, you’re the best !
Certainly, you’re most welcome. Glad it helped. 🙂
Hi! Thank you for your great tutorial! That is awesome. I have a question. I have a json file which contains multiple data for the posts. So, right I can add the first array of data using json_decode. But i need to create more posts using json. Thank you!
Hi Zavrazhnov,
Thanks and I’m glad that the article was a great help to you. As for parsing a json object within the json file, you’ll have to use json_decode and then loop json using a foreach statement. Review this example from another one of my websites. Hope this helps.
this is working great
Thanks
Great to hear, and glad to know it helped you!
what’s wrong, why can’t add an iframe code ( )
the iframe code is always lost when viewed in a post
WordPress treats iframe as malicious code, sanitizes it. You’ll have to use a plugin design to include iframes.
Great Tutorial I created the bulk posts in WordPress using this tutorial but I have a doubt.
Is creating posts is programmatically is similar to creating the post manually, is there is any effect on SEO. I mean after creating post the WordPress system ping the post to pinging services like that .
My clear doubt is, “Is programmatically creating WordPress posts effects the SEO ?”
Hi Bala! Thanks and I’m glad that you found the tutorial to be helpful. As for “effect on SEO”, that’s really a loaded question. A greater, more in-depth conversation would need to be had to discover whether or not programmatically creating WordPress posts effects SEO. There are so many different factors to consider when attempting to realize the value of such a statement. As for content ranking, there really is no substitution for human-written content — even AI and Machine Learning have not gotten to the level to “fool” search engines, although well on their way. That being said, if you do automate content creation using WordPress, then I recommend that content created or curated be presented in a unique manner that doesn’t suggest duplicate content. Doing so, this will allow for the content to reap the greatest opportunity for search result ranking for given content topic. Hope this helps. Feel free to respond and share a bit more detail about your question.
Hi Alvin,
Any suggestions for adding the new blog post using a cron job?
Thanks for all the great work you shared with all of us.
Hello John! Thanks for your comment and glad you find this post insightful. As for adding a new blog post using a cron job, who do you host your website with?
Hi Alvin, I have a variation on this that I’m looking for help with.
I want to update one page on my site with new content every day – it’s a daily thought of the day type thing.
The content is already written for the whole year – I want the page to refresh each day with that day’s thought – and then to repeat year after year with the same 365/6 thoughts.
Any suggestions?
Hi Josh – You’re essentially updating the content of a post using its ID, replacing old content with new each day. You’ll likely have to create a cron job that runs daily to execute the previous sentence. Hope this helps.