Empty custom database tables with wp site empty

When using wp site empty, make sure you reset any custom tables storing content too.

wp site empty (doc) is a great command for quickly resetting your WordPress database of content, without resetting the site’s configuration. However, when using a plugin like Posts 2 Posts, which registers custom database tables, you need to make sure its custom database tables are also emptied. Using Posts 2 Posts as an example, here’s how you can make sure its custom database tables are emptied when you call wp site empty:

<?php
/**
 * Requires WP-CLI v0.24.0-alpha or later because it needs https://github.com/wp-cli/wp-cli/pull/2647
 */
if ( defined( 'WP_CLI' ) && WP_CLI ) {
	WP_CLI::add_hook( 'after_invoke:site empty', function(){
		global $wpdb;
		foreach( array( 'p2p', 'p2pmeta' ) as $table ) {
			$table = $wpdb->$table;
			$wpdb->query( "TRUNCATE $table" );
		}
	});
}