How to create WordPress pages with just pure PHP

I’ve seen alot of people ask how to create pages within WordPress with some simple PHP code so I thought i’d give answering it a go.

You’ll be pleased to know that the solution is pretty straight forward and nothing to strenuous.

We’ll start off by defining a function to handle creating pages in WordPress, you could use this function in your themes function file or indeed in any custom WordPress Plugin.

if(!function_exists('daves_create_page')):
    function daves_create_page( $slug, $option, $page_title = '', $page_content = '', $post_parent = 0){
        global $wpdb;
        $option_value = get_option($option);
        if ($option_value>0) :
            if (get_post( $option_value )) :
	        // Page exists
	        return;
	    endif;
	endif;
	$page_found = $wpdb->get_var("SELECT ID FROM " . $wpdb->posts . " WHERE post_name = '$slug' LIMIT 1;");
	if ($page_found) :
	    // Page exists
	    return;
	endif;
	$page_data = array(
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_author' => 1,
            'post_name' => $slug,
            'post_title' => $page_title,
            'post_content' => $page_content,
            'post_parent' => $post_parent,
            'comment_status' => 'closed'
        );
        $page_id = wp_insert_post($page_data);
        update_option($option, $page_id);
    }
endif;

After defining this function we can call it into play very simply with the following.

daves_create_page(
    esc_sql( _x('example_page', 'page_slug', 'davespage') ),
    'daves_page_id',
    __('Example Page', 'davespage'),
    'Some example content.'
);

Hope this helps some people out, as you can see, pretty straight forward and unobtrusive.