how do I programically create a page in WordPress if it doesn’t exist already?

how do I programically create a page in WordPress if it doesn’t exist already?

Related posts

Leave a Reply

3 comments

  1. I want to write a plugin and to put some html controls in a page which will automatically create when user install the plug in

    Based on that comment, you want to hook a function to your plugin’s activation hook, which inserts a WordPress post object into the database;

    function my_plugin_activate()
    {
        wp_insert_post(array(
            'post_type' => 'page',
            'post_title' => 'Page Title',
            'post_content' => 'Page Content',
            'post_name' => 'page-slug',
        ));
    }
    register_activation_hook(__FILE__, 'my_plugin_activate');
    
  2. How will you identify that page? Assuming you have a specific title, use something like

    if( get_page_by_title('my_title') === false ) // page doesn't exist
    {
        // insert the page using wp_insert_post
    }
    

    If you need help with wp_insert_post, please comment.

  3. You can implement a function that intercepts the template_redirect action/filter, and inside that function include the theme’s header and footer, while creating your own content to put into the body of the page. See the API link (above) for an example.

    Here’s a tutorial on the web.