programmatically create wordpress page

programmatically create wordpress page using theme code

Many times client want predefined page in wordpress site when theme is activated. Here in this wordpress tutorial, we will show you how to programmatically create page or posts in wordpress website.

programmatically create wordpress page

If you want to create custom page with content than you can use following code. You just need to open “functions.php” file. (File can be found in theme folder).


if (isset($_GET['activated']) && is_admin()) {
$new_page_template = ''; //ex. template-custom.php. Leave blank if you don't want a custom page template.

//don't change the code bellow, unless you know what you're doing
$page_check = get_page_by_title('This is the page custom title');
$new_page = array(
'post_type' => 'page',//define post or page
'post_title' => 'This is the page custom title',
'post_content' => 'This is the page custom content',
'post_status' => 'publish',
'post_author' => 1,
);
if(!isset($page_check->ID)){
//create page in wordpress
$new_page_id = wp_insert_post($new_page);
if(!empty($new_page_template)){
update_post_meta($new_page_id, '_wp_page_template', $new_page_template);
}
}

}

You just need to copy and paste above code into functions.php file. This will create custom page in wordpress website. programmatically created page will look like as follows:

programmatically create wordpress page
programmatically create wordpress page

programmatically create wordpress post

If you want to create wordpress post programmatically than use following code.


if (isset($_GET['activated']) && is_admin()) {
$new_page_template = ''; //ex. template-custom.php. Leave blank if you don't want a custom page template.

//don't change the code bellow, unless you know what you're doing
$page_check = get_page_by_title('This is the page custom title');
$new_page = array(
'post_type' => 'post',//define post or page
'post_title' => 'This is the page custom title',
'post_content' => 'This is the page custom content',
'post_status' => 'publish',
'post_author' => 1,
);
if(!isset($page_check->ID)){
//create page in wordpress
$new_page_id = wp_insert_post($new_page);
if(!empty($new_page_template)){
update_post_meta($new_page_id, '_wp_page_template', $new_page_template);
}
}

}

You need to copy and paste above code in to functions.php file. With above code you can create custom post type’s post programmatically.

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

Leave a Reply

Your email address will not be published.