How to create Wordpress pages with just pure PHP

November 27, 2011    create wordpress pages Wordpress wordpress and 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.

    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
	$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.

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

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

blog comments powered by Disqus