Add Snippet To Project
Are you tired of manually creating a new page every time you install a WordPress theme? Do you wish there was an easier way to streamline this process? Well, you’re in luck! In this article, we’ll show you how to automatically create a page on theme activation, saving you time and effort. With this neat trick, you’ll be able to quickly set up a default page layout every time you switch to a new theme. So let’s dive in and discover how to simplify your website creation process.
function wpturbo_create_page_on_theme_activation() {
$page_title = 'About Us';
$page_content = 'This is the about us page content';
$page_check = get_page_by_title($page_title);
if( !$page_check ) {
$page_data = array(
'post_type' => 'page',
'post_title' => $page_title,
'post_content' => $page_content,
'post_status' => 'publish',
'post_author' => 1,
);
wp_insert_post( $page_data );
}
}
add_action( 'after_switch_theme', 'wpturbo_create_page_on_theme_activation' );
The code snippet above demonstrates how to create a new page in WordPress automatically when a theme is activated. This can be useful in situations where you want to ensure that certain essential pages, like an "About Us" or "Contact" page, are always available when a user activates your theme.
Let’s break down how this code works:
-
First, we define a function called
wpturbo_create_page_on_theme_activation()
. This function will be responsible for creating the new page. -
Inside the function, we define two variables:
$page_title
and$page_content
. These variables hold the desired title and content for the new page. -
We then use the
get_page_by_title()
function to check if a page with the given$page_title
already exists. This function returns the page object if the page already exists, andfalse
if it does not. -
Next, we use an
if
statement to check if$page_check
(the result ofget_page_by_title()
) isfalse
. This means that the page does not exist and needs to be created. -
Inside the
if
statement, we create an array called$page_data
that holds all the necessary information for creating the new page. This includes the post type (which is set to'page'
), the title, content, status (set to'publish'
), and author (in this case, set to1
). -
Finally, we use the
wp_insert_post()
function to insert the new page into the database using the$page_data
array. -
We hook the
wpturbo_create_page_on_theme_activation()
function to theafter_switch_theme
action. This ensures that the function is executed immediately after the theme is activated.
By following these steps, your theme will automatically create the specified page if it does not already exist when the theme is activated. This can be a helpful time-saving feature for users, as they don’t need to manually create the page themselves.