How to create posts and pages programmatically in WordPress

Are you looking for an alternative to add posts and pages to your site? You’ve come to the right place. In this guide, we’ll show you how to create posts and pages programmatically in WordPress.

As the biggest Content Management System (CMS) in the world, publishing posts and pages is one of its main features. Initially, WordPress was created to help website owners create and manage their sites. Nowadays, it has become a complete solution for all kinds of sites.

Apart from being popular among blogs and online stores, there are many other types of websites built with WordPress, from catalogs to directories to job boards, wikis, personal portfolios, forums, or even social media networks.

All websites (except static sites) publish some type of content with a certain frequency. Posts and pages are the most basic type of content compared to other types like products, comments, reviews, and more.

Before we see why and how to create posts and pages programmatically, let’s better understand the differences between them. This will help you follow good practices and avoid any possible issues.

Difference between post and pages

1) Posts

In WordPress, posts are the way a website delivers valuable and updated content to its users. It is expected that a website publishes posts regularly, but it varies a lot depending on the type of site. A news blog will post content much more often than a corporate site, so the number of posts on a website can have varies a lot.

Posts are commonly listed in reverse chronological order on websites. That means that the latest published post will be visible at the top of the list. But you can also make a post sticky and display it permanently somewhere on your website.

When you have a large site with hundreds or even thousands of posts, the correct usage of taxonomies is key to allow users to find any post with ease. Keep in mind that they will navigate through categories and subcategories, look at the tags list, and using the search box. For more information about this, check out our post on how to add categories to the menu.

2) Pages

Unlike posts, pages are intended to be more static than posts. However, they often include content that is constantly updated. For example, a shop page or category page will certainly have updated content, but they’re still pages because you don’t publish a new shop page for each product update.

Pages like “About us”, “Who we are”, “Contact” or “Documentation” are mainly static content, so they’re usually not updated very often.

Another difference between posts and pages is tags and categories. Posts can have categories and tags to facilitate their organization and to be used in search boxes, while pages lack taxonomies.

For more information about this, check out our guide that explains different ways to create pages. Additionally, we recommend you have a look at our tutorial to change the post type in WordPress.

Why create posts and pages programmatically?

You probably know how to create posts and pages from the WordPress dashboard. You simply have to go to Posts/Pages > Add New and add a name, content, choose a category, and so on.

However, if you’re working on a more advanced project, you may need an alternative solution. For example, if you need to automate the publishing process to meet a specific requirement or restrict access for certain users. If this is your case, learning to create WordPress posts and pages programmatically will be very useful.

How to publish WordPress posts and pages programmatically

In this section, we’ll show you how to create posts and pages programmatically in WordPress. We’ll explain the code below but it’s recommended that you have some programming skills to make the process easier.

NOTE: As we’ll edit some core files, before we start, we recommend you backup your site. On top of that, create a child theme if you don’t have one yet or use any of these child theme plugins.

How to publish posts

Here is the full script that will automatically publish a post and the explanation of the code below. Keep in mind that you have to paste the code in the functions.php file of your child theme

add_action( 'admin_init', 'QuadLayers_publish_post' );

function QuadLayers_publish_post() {
 
    if ( get_option( 'post_is_published_01' ) != 'yes' ) {
		 $postType = 'post'; 
		 $userID = 1; 
		 $categoryID = '1'; 
		 $postStatus = 'publish';  
		 $leadTitle = 'A post was published '.date("n/d/Y");
		 $leadContent = '<h1>Programatically posted</h1><p>This post was published programatically and meta option saved as <b>post_is_published_01</b>. A PHP srcipt in the functions.php file of the child theme.</p>';
		 $leadContent .= ' <!--more--><p>Expensive they are, but they are totally worth it.</p>';
		 
		 # build time&date
		 $timeStamp = $minuteCounter = 0;  
		 $iCounter = 1; 
		 $minuteIncrement = 1; 
		 $adjustClockMinutes = 0; 
		 $minuteCounter = $iCounter * $minuteIncrement; 
		 $minuteCounter = $minuteCounter + $adjustClockMinutes; 
		 $timeStamp = date('Y-m-d H:i:s', strtotime("+$minuteCounter min")); 

	 	 # build post
		 $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)
		 );	
		 # publish it !
		 $post_id = wp_insert_post($new_post);

  update_option( 'post_is_published_01', 'yes' );
    }
}

As we can’t know if a post exists before publishing it, we need to register somewhere that our post is published. If we don’t do this, our post will be published every time a backend screen is loaded.

The options table of the database is the correct place to do this. We are storing an option called post_is_published_01 after publishing the post, with the update_option() function. And checking if the option exists with the get_option(). If this option is present on the database, the script will not do anything.

To run the script again you can simply change the name of the option to post_is_published_02 or whatever you want.

Inside the if() conditional, you can see how we define the content of the post on the first block. And we need to prepare the time and date to match WordPress requirements.

Finally, the function in charge of post publishing is wp_insert_post(), which attaches all the previous data declared in the function

publish post programatically

How to publish pages

Publishing pages programmatically is a bit more simple. In this script, we won’t a database option to check if page has been already published.

As pages have a different function than posts and the WordPress functions for posts and pages are different, we can use the get_page_by_title() function to check if we have published a page with the same title before. And then we insert the information about the page such as author, title, name, and so on.

Use the following script to publish a page on your WordPress website:

add_action( 'admin_init', 'QuadLayers_publish_page' );

function QuadLayers_publish_page(){
	$check_page_exist = get_page_by_title('Page published programatically', 'OBJECT', 'page');
	if(empty($check_page_exist)) {
		$page_id = wp_insert_post(
			array(
			'comment_status' => 'close',
			'ping_status' => 'close',
			'post_author' => 1,
			'post_title' => ucwords('Page published programatically'),
			'post_name' => strtolower(str_replace(' ', '-', trim('Page published programatically'))),
			'post_status' => 'publish',
			'post_content' => '<p>This is the content of the page, html tags are allowed here</p>', 
                        'post_type' => 'page', 'post_parent' => 'id_of_the_parent_page_if_it_available' ) ); 
        } 
}

publish page programatically

Conclusion

In summary, in this guide we’ve seen some key differences between posts and pages. Posts tend to be more dynamic and have taxonomies and cateogories, whereas pages tend to be more static and don’t have taxonomies.

Even though in WordPress you can easily create pages and posts with the built-in editor, learning to do so with a bit of coding can be useful in some situations to automate the publishing process to meet specific requirements. If that’s your case, learning how to create posts and pages programmatically can make your life easier.

In this guide, we’ve seen how to create posts and pages and the differences in the scripts. We encourage you to take these scripts as a base and customize them for your site.

Have you tried creating posts and pages with a bit of code? Did it work as you expected? Let us know in the comments section below!

If you enjoyed this post, you may also be interested in: