How to create Wordpress pages with just pure PHP

November 27, 2011

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(!functionexists(‘davescreatepage’)): function davescreatepage( $slug, $option, $pagetitle = ”, $pagecontent = ”, $postparent = 0){ global $wpdb; $optionvalue = getoption($option);

    if ($option_value>0) :
        if (get_post( $option_value )) :
        // Page exists

$page_found = $wpdb->get_var("SELECT ID FROM " . $wpdb->posts . " WHERE post_name = '$slug' LIMIT 1;");
if ($page_found) :
    // Page exists

$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);


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

davescreatepage( escsql( _x(‘examplepage’, ‘pageslug’, ‘davespage’) ), ‘davespage_id’, __(‘Example Page’, ‘davespage’), ‘Some example content.’ );

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

About me

Hello! I'm David Heward, how are you going? I'm a Senior Devops/Build Engineer, specialising in AWS & Cloud Automation. Based in London. Strong 10+ year background in Software development. Have a read of my blog. Have a look at some of my working projects. Contact me at @davehewy or on Linkedin.