Skip to content

Instantly share code, notes, and snippets.

@ryanshoover
Created December 15, 2022 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanshoover/72f3b53fa5ab95396ea6835737aa79b1 to your computer and use it in GitHub Desktop.
Save ryanshoover/72f3b53fa5ab95396ea6835737aa79b1 to your computer and use it in GitHub Desktop.
Delete a WordPress network's site content when a single site is deleted.
<?php
/**
* Helper function to remove a directory and all its contents.
* PHP requires you to remove each file individually and delete
* a directory only when it's empty.
*
* @param string $path Absolute path to a directory.
*/
function remove_directory( $path ) {
$files = glob( $path . '/*' );
foreach ( $files as $file ) {
is_dir( $file ) ? removeDirectory( $file ) : unlink( $file );
}
rmdir( $path );
}
/**
* Cleanup orphaned tables during site deletion
*
* @param $site WP_Site class for the site that was just deleted.
*/
function delete_site_contents( $site ) {
global $wpdb;
// Get the list of tables using the site's prefix.
$table_list = $wpdb->get_col(
$wpdb->prepare(
"SHOW TABLES LIKE %s;",
$wpdb->esc_like( "{$wpdb->base_prefix}{$site->site_id}_" ) . '%' )
);
// Loop through those tables and delete them 1 by 1.
foreach ( $table_list as $table ) {
$wpdb->query( $wpdb->prepare( "DROP TABLE %s", $table ) );
}
// Delete the site's uploads as well.
$upload_dir = wp_get_upload_dir();
$site_upload_path = $upload_dir['path'] . '/site/' . $site->site_id;
remove_directory( $site_upload_path );
}
add_action( 'wp_delete_site', 'delete_site_contents' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment