I just had a request not too long ago for a way that someone could automate the addition of content when a theme is turned on. Luckily, there’s a function within WordPress that allows this to work!
Online information for this function can be found here.
Here’s the code snippet below:
<?php
function mytheme_after_switch_theme() {
$pages = array(
array(
'name' => 'page-name',
'title' => wp_strip_all_tags( 'Page Name' ),
'content' => "<!-- wp:paragraph --><p>This is the page content.</p><!-- /wp:paragraph -->",
),
);
$template = array(
'post_type' => 'page',
'post_status' => 'publish',
'post_author' => 1
);
foreach( $pages as $page ) {
$my_pages = array(
'post_name' => $page['name'],
'post_title' => $page['title'],
'post_content' => $page['content']
);
$my_page = array_merge( $my_pages, $template );
wp_insert_post( $my_page );
}
flush_rewrite_rules();
}
add_action('after_switch_theme', 'mytheme_after_switch_theme');
?>
Name: this is the slug that will be created for the page.
Title: self explanatory.
Content: this is the editor block. You can put regular HTML in this. If you want it to be properly Gutenberg-friendly, you can search for the proper <!– tags –> to help WordPress understand what’s what.
For this to work, you want to add this function to your theme folder. I have an /inc/ directory, and I keep my functions in files that match their name. So, for me, this function exists in /inc/after_switch_theme.php.
If you want to use this with a plugin, you can find the post here!
Leave a Reply