Add content on plugin activation!

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. For a plugin, you can also do this with the register_activation_hook command.

Here’s the code snippet below:

function activate_myPlugin() {
	$pages = 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 );
register_activation_hook( __FILE__, 'activate_myPlugin' );

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 index.php file within your plugin. You want it to fire off as soon as the plugin is activated, and the index.php file is the first file WordPress will check.

If you want to use this with a theme, you can find the post here!

By Sharon

Hello there! I'm a web developer in Louisville, Kentucky. I started on this career path by purchasing an O’Reilly PHP book from Barnes & Noble in 1999. Since then, my desire to learn as much as I can about web site building and server maintenance has grown. I love technology and what it can do to simplify our lives and make it more interesting all at the same time. Seeing a creative design come to life and bringing it into the web world is my favorite puzzle to solve. My server experience is based around launching WordPress-friendly servers — Linux (Ubuntu and Centos flavors), Apache, MySQL, and PHP. I have worked with various modules, extensions, installs such as ImageMagick, LetsEncrypt, Sass, LESS, and the Homebrew family of extension. My main love has been with PHP, and my CMS of choice has been WordPress since its inception in 2003. I find it flexible, secure, easy to design around, and so customizable. My strengths are in developing from-scratch plugins and themes for the WordPress CMS with a strong background in PHP and MySQL development.

1 comment

Leave a comment

Your email address will not be published.