Deluxe Blog Tips About Projects

Auto Create And Assign Static Homepage In WordPress

For some themes, when the homepage or more exactly - the front page, is well designed, and users have to follow the theme documentation to create such that page to make it look the same as in the demo. In this article, I'll show you a simple way to check if a static homepage has been assigned and automatically create it if it's missed.

Auto Create Static Homepage

There are 2 options in WordPress that control static homepage: show_on_front - type of homepage (latest posts or static page) and page_on_front - which page is shown on homepage. Here's the snippet that checks these options and automatically creates a Homepage page:

function mytheme_create_homepage()
{
    if ( 'page' === get_option( 'show_on_front' ) && get_option( 'page_on_front' ) )
        return;

    $homepage = wp_insert_post( array(
        'post_title'   => 'Homepage',
        'post_status'  => 'publish',
        'post_type'    => 'page',
        'post_content' => 'Any content here',
    ) );
    if ( $homepage )
    {
        update_option( 'show_on_front', 'page' );
        update_option( 'page_on_front', $homepage );
    }
}