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:

<?php
function activate_myPlugin() {
	$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();
}
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!

,

One response to “Add Content on Plugin Activation”

Leave a Reply

Your email address will not be published.