Warning: Undefined array key "HTTP_ACCEPT_LANGUAGE" in /home/admin/domains/wpxpo.com/public_html/index.php on line 40
How to Create a Post or Page Programmatically in WordPress? - WPXPO

How to Create a Post or Page Programmatically in WordPress?

As a WordPress developer, it is easy for me to create WordPress posts or pages programmatically. But most of the WordPress users are beginners and find it difficult. That’s why I am writing this blog post to make it easier for you. So, How do I make a Programmatically page in WordPress?

To make a post or page programmatically you can follow these two simple steps.

1. First of all, insert the “wp_insert_post” code in the functions.php file of your current theme.

2. Then you need to add the required data of the page or post in the array. For example, post_type, post_title, post_status, post_author and post_name.

Why Do You Need to Create a Post or Page Programmatically?

In many cases creating a dynamic page while the plugin or theme activated is necessary. Needless to say, this gives your post or page an extra layer of personality. This way you get the best of both worlds. In WordPress, you can easily create a page or post from the frontend. However, creating a page by coding is a little bit tricky. You will need to put some code inside your theme function or plugin’s PHP file to do so.

You can create a post or page programmatically using two different methods. For the convenience of our users, we will describe both methods in detail. So, without further ado, let’s get to it.

Method 1: Creating a Post or Page Programmatically with the Insert Function

First of all, you will need to use the wp_insert_post WordPress function in this method. For creating any post you have to use this WordPress default function called “wp_insert_post”. See the code snippet below to insert a WordPress page programmatically. 

$page_slug = 'test-page-title'; // Slug of the Post
$new_page = array(
    'post_type'     => 'page', 				// Post Type Slug eg: 'page', 'post'
    'post_title'    => 'Test Page Title',	// Title of the Content
    'post_content'  => 'Test Page Content',	// Content
    'post_status'   => 'publish',			// Post Status
    'post_author'   => 1,					// Post Author ID
    'post_name'     => $page_slug			// Slug of the Post
);

if (!get_page_by_path( $page_slug, OBJECT, 'page')) { // Check If Page Not Exits
    $new_page_id = wp_insert_post($new_page);
}

post_title and post_content are the basic required arguments for the insertion of any post. Some of the other major arguments of the wp_insert_post function are given below.

  • “post_author: Post author ID.
  • post_date: When the post has been published.
  • post_content: Content of the post.
  • post_title: Title of the post.
  • post_name: Slug of the post.
  • post_excerpt: Excerpt of the post.
  • post_status: Post status.
  • post_type: Post Type slug.
  • comment_status: Are comments open or not.
  • “post_category”: Category IDs Array.
  • “tags_input”: Array of tag names, slugs, or IDs. Default empty.
  • “tax_input”: Array of taxonomy terms keyed by their taxonomy name.
  • “meta_input”: Array of post meta values keyed by their post meta key.

If you want to learn more detailed instructions regarding this, kindly read the WordPress documentation page.

If you don’t like the above-mentioned method there is another method waiting for you below. Continue reading to learn about the second method.

Method 2: Creating a Post or Page Programmatically with Database Query

While using the above method you can easily create a page or post, it is not the only way. We know some of you may want to learn how to do it using WordPress direct SQL Query. See the code snippet below to insert a WordPress page directly into the database via SQL.

global $wpdb;
$tablename = $wpdb->prefix . "posts";

$post_type		= "page";
$post_title		= "Test Page Title2";
$post_content	= "Test Page Content2";
$post_status	= "publish";
$post_author	= 1;
$post_name		= "test-page-title2";

if (!get_page_by_path( $post_name, OBJECT, 'page')) { // Check If Page Not Exits
    $sql = $wpdb->prepare("INSERT INTO `$tablename` (`post_type`, `post_title`, `post_content`, `post_status`, `post_author`, `post_name`) values (%s, %s, %s, %s, %d, %s)", $post_type, $post_title, $post_content, $post_status, $post_author, $post_name);

    $wpdb->query($sql);	
}

Here $wpdb is the global variable of the WordPress database. The “Prepare” function is used to validate data and prevent SQL injection from hackers. On the other hand, “query” directly runs the SQL. 

Creating Page Programmatically after Plugin Activation

The plugin developer needs to create a page once the plugin has been activated. Action hook helps the plugin developer to do this. Here is the sample code:

define( 'PLUGIN_FILE_PATH', __FILE__ );

register_activation_hook( PLUGIN_FILE_PATH, 'insert_page_on_activation' );

function insert_page_on_activation() {
  if ( ! current_user_can( 'activate_plugins' ) ) return;

  	$page_slug = 'test-page-title'; // Slug of the Post
    $new_page = array(
        'post_type'     => 'page', 				// Post Type Slug eg: 'page', 'post'
        'post_title'    => 'Test Page Title',	// Title of the Content
        'post_content'  => 'Test Page Content',	// Content
        'post_status'   => 'publish',			// Post Status
        'post_author'   => 1,					// Post Author ID
        'post_name'     => $page_slug			// Slug of the Post
    );
	if (!get_page_by_path( $page_slug, OBJECT, 'page')) { // Check If Page Not Exits
		$new_page_id = wp_insert_post($new_page);
	}
}

You can insert this code into your plugin’s main PHP file.

Creating Page Programmatically after Theme Activation

You will need this code if you want to create a page after the activation of the theme. All you need to do is, add this code directly to your theme’s function.php file.

add_action( 'after_switch_theme', 'create_page_on_theme_activation' );
function create_page_on_theme_activation() {
  	$page_slug = 'test-page-title'; // Slug of the Post
    $new_page = array(
        'post_type'     => 'page', 				// Post Type Slug eg: 'page', 'post'
        'post_title'    => 'Test Page Title',	// Title of the Content
        'post_content'  => 'Test Page Content',	// Content
        'post_status'   => 'publish',			// Post Status
        'post_author'   => 1,					// Post Author ID
        'post_name'     => $page_slug			// Slug of the Post
    );
	if (!get_page_by_path( $page_slug, OBJECT, 'page')) { // Check If Page Not Exits
		$new_page_id = wp_insert_post($new_page);
	}
}

Being able to create a post or page programmatically gives you the much-needed boost to get a head start. In a world where 547200 websites are created daily, this could your ace in the hole. With PostX – Gutenberg Post Blocks you reap the benefits of both the plugin and the custom coding. Here at WPXPO, it is our goal to deliver the best service possible. For more requests feel free to contact us. To get more similar easy how-to, informative articles keep visiting our blog.

Like this article? Spread the word
Omith Hasan

Written byOmith Hasan

I started my WordPress Journey back in 2016 when I discovered how easy it was to create a blog using WordPress. So, I learned WordPress, Content Writing, and Search Engine Optimization to start my blogging Journey. Then, I learned about WooCommerce and also started writing about it. I love to write problem-solving-related content to help and educate WordPress and WooCommerce users.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get Discount