Programatically create a page

Is it possible to programatically create a page? I want to make it so that I can create a template file in a theme and be able to point links to that page without having to rely on the user to go and manually create a page using the tempalte.

Is that possible?

Read More

Update: Solution so Far

This is what I have come up with so far:

add_action( 'init', 'add_virtual_page_template' );

function add_virtual_page_template()
{
    global $wp, $wp_rewrite;

    $wp->add_query_var( 'template' );
    add_rewrite_endpoint( 'fish', EP_ROOT );

    $wp_rewrite->add_rule(  'fish/?', 'index.php?template=fish', 'top' );
    $wp_rewrite->flush_rules();
}

add_action( 'template_redirect', 'add_virtual_page_redirect' );

function add_virtual_page_redirect()
{

    global $wp;
    $template = $wp->query_vars;

    if ( array_key_exists( 'template', $template ) && $template['template'] == 'fish' )
    {

    global $wp_query;
    $wp_query->set( 'is_404', false );
    include( get_stylesheet_directory() . '/page-fish.php' );
    exit;
}

Both of these are in the functions.php file of my theme.

This code successfully serves the content of page-fish.php as if I had created a page and set it as the template.

The one thing that has come up so far: the URL of the site using this method is

www.url.com/login/

However, if I create a page and set the template manually, the URL is as following:

www.url.com/login

It is relatively minor, but is there some way of fixing this issue?

Are there any other issues that I might run into using the overall method that I used here?

Related posts

1 comment

  1. You can try

    // add a new page
    $args = array (
        'post_type'   => 'page', 
        'post_title'  => 'My New Page',
        'post_status' => 'publish',
    ); 
    $pid = wp_insert_post( $args );
    
    // add a custom template file to the newly created page
    if( $pid > 0 )
        add_post_meta( $pid, '_wp_page_template', 'custom-template.php' );
    

    where we set the page template file via the _wp_page_template meta key.

Comments are closed.