Delete WordPress Sample Content Automatically

Published on

WordPress ships with 2 pieces of sample content. The Sample Page and a Sample Post content have been part of the WordPress base install for years. I wish WordPress gave an option to install WordPress without sample content, but as far as I know that’s not on the feature map. There may be times when you will need to delete that sample content programatically.

If you are running a WordPress Multisite network, you may not want that sample content created each time you add a new site. Let’s create a WordPress action, which we can insert into our plugin, or the default theme for the multisite install.


add_action( 'wpmu_new_blog', 'execute_site_actions', 10, 6 );

This will call a new function that we’ll create called execute_site_actions(). In this function, we can execute as many actions or events that we want to happen. I have used this to create default categories, switch the new site to a different theme, or created some base content for the new site.

In our case, we just want to delete that sample content. The function accepts several parameters. For this example, we will only need the first one, the $blog_id. For a full explanation of what each parameter is for, be sure to consult the WordPress Codex.


function execute_site_actions( $blog_id, $user_id, $domain, $path, $site_id, $meta ) {
    switch_to_blog($blog_id);

    // Find and delete the WP default 'Sample Page'
    $defaultPage = get_page_by_title( 'Sample Page' );
    wp_delete_post( $defaultPage->ID, $bypass_trash = true );

    // Find and delete the WP default 'Hello world!' post
    $defaultPost = get_posts( array( 'title' => 'Hello World!' ) );
    wp_delete_post( $defaultPost[0]->ID, $bypass_trash = true );

    restore_current_blog();
}

The first line, switch_to_blog($blog_id) is very important. We need to switch to the blog that we just created, in order to search for the sample content we are deleting. Now that we are using the newly created blog in our code, we can search for the Sample Page and Sample Post, and call wp_delete_post on both to delete it. In this example I have told it to skip the trash, but you can chose whichever is best for you.

Lastly we call restore_current_blog() to return to our previous state. You now have a clean and fresh WordPress site!