Programmatically create WordPress Posts and Pages using PHP.

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:

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! 😉

Please subscribe to my YouTube channel to receive tutorial alerts.

Share:
Written by Alvin Brown
He's an experienced and passionate serial entrepreneur, founder and publisher of Kickstart Commerce. Alvin possesses a great love for startups dominating their market using profitable digital strategies for greater commerce.