Here, we discussed how to automatically create a WordPress Category. Now we’ll extend it a bit further by showing you how to create a WordPress page. We use this in our themes that have a static home page. First we create the necessary ‘Blog’ and ‘Home’ pages, then we tell WordPress to use a static home page.
So onto the code:
First you want to see if the page you are creating already exists:
|
1 2 3 4 |
$home = get_page_by_title( 'Home' ); if (!$home) { ... } |
If it doesn’t the next thing to do is create it:
|
1 2 3 4 5 6 |
$post = array( 'post_name' => 'Home', 'post_status' => 'publish', 'post_title' => 'Home', 'post_type' =>'page' ); $home_id = wp_insert_post($post); |
All of this goes in your functions.php file, but we don’t want to do this every time functions.php is loaded, so we wrap this in a function, and also only execute this when we’re in the admin panel.
|
1 2 3 4 5 6 7 |
add_action( 'after_setup_theme', 'UNIQUE_PREFIX_setup_theme' ); function UNIQUE_PREFIX_setup_theme(){ if (is_admin() ) { ... } } |
putting it all together, we have this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
add_action( 'after_setup_theme', 'UNIQUE_PREFIX_setup_theme' ); function UNIQUE_PREFIX_setup_theme(){ if (is_admin() ) { $home = get_page_by_title( 'Home' ); if (!$home) { $post = array( 'post_name' => 'Home', 'post_status' => 'publish', 'post_title' => 'Home', 'post_type' =>'page' ); $home_id = wp_insert_post($post); } } } |
Any questions? Ask us in the comments!


