Skip to content

Instantly share code, notes, and snippets.

@vncloudsco
Created April 15, 2023 15:47
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 vncloudsco/d851fc090d9542d8a4e511a563ec8fdc to your computer and use it in GitHub Desktop.
Save vncloudsco/d851fc090d9542d8a4e511a563ec8fdc to your computer and use it in GitHub Desktop.
function wp_optimize_unused_tables() {
global $wpdb;
// Danh sách các bảng được cài đặt mặc định
$default_tables = array(
'wp_users',
'wp_usermeta',
'wp_posts',
'wp_comments',
'wp_links',
'wp_options',
'wp_postmeta',
'wp_terms',
'wp_term_taxonomy',
'wp_term_relationships',
'wp_commentmeta'
);
// Lấy danh sách tất cả các bảng
$all_tables = $wpdb->get_results( "SHOW TABLES", ARRAY_N );
// Lặp qua từng bảng và kiểm tra nếu không được sử dụng
foreach ( $all_tables as $table ) {
$table_name = $table[0];
if ( ! in_array( $table_name, $default_tables ) ) {
$result = $wpdb->get_var( "SELECT COUNT(*) FROM " . $table_name );
if ( $result == 0 ) {
// Nếu bảng không có dữ liệu, xóa bảng đó
$wpdb->query( "DROP TABLE IF EXISTS " . $table_name );
error_log( 'Dropped unused table ' . $table_name );
}
}
}
}
// Thêm function vào cron job để thực thi mỗi ngày
add_action( 'wp', 'schedule_daily_optimization' );
function schedule_daily_optimization() {
if ( ! wp_next_scheduled( 'wp_optimize_unused_tables_daily' ) ) {
wp_schedule_event( time(), 'daily', 'wp_optimize_unused_tables_daily' );
}
}
add_action( 'wp_optimize_unused_tables_daily', 'wp_optimize_unused_tables' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment