Created
December 15, 2022 19:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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