How To Programmatically Create a WordPress Page

I would like to create a WordPress page from my widget, How can I programmatically create a WordPress page. What WordPress native function I can use

You can use the wp_insert_post function to create a page from your widget, meanwhile, you need to use get_page_by_title and the_slug_exists to check if the page title and slug has been taken or not.

$author_id = 1; // the id of author 
$title = 'My First Page'; // title of your first post
$page_check = get_page_by_title($title );
$post_id = null;
$page_content = '';
$slug  = sanitize_title($title);

if( null == $page_check && !the_slug_exists($slug)) {

    $post_id = wp_insert_post( array(
	    'post_type' => 'page',
	    'post_title' => $title ,
	    'post_content' => $page_content,
	    'post_status' => 'publish',
	    'post_author' => $author_id,
	    'post_slug' => $slug  ));
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments