Created
November 10, 2025 05:25
-
-
Save kartikparmar/b739b04e82fde2944b8451c5f06dc067 to your computer and use it in GitHub Desktop.
Remove Bookings older than 3 years
This file contains hidden or 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 | |
| /** | |
| * Deletes a batch of old bookings (older than 2 years) | |
| * Returns true if more bookings remain, false if completed. | |
| */ | |
| function bkap_delete_old_booking_batch( $batch_size = 200 ) { | |
| global $wpdb; | |
| $two_years_ago = gmdate( 'YmdHis', strtotime( '-3 years' ) ); | |
| // Fetch batch of old booking IDs | |
| $booking_ids = $wpdb->get_col( $wpdb->prepare( | |
| "SELECT pm.post_id | |
| FROM {$wpdb->postmeta} pm | |
| INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID | |
| WHERE p.post_type = %s | |
| AND pm.meta_key = '_bkap_end' | |
| AND pm.meta_value < %s | |
| GROUP BY pm.post_id | |
| LIMIT %d", | |
| 'bkap_booking', | |
| $two_years_ago, | |
| $batch_size | |
| ) ); | |
| // No old bookings left | |
| if ( empty( $booking_ids ) ) { | |
| return false; | |
| } | |
| $ids_placeholder = implode( ',', array_map( 'intval', $booking_ids ) ); | |
| // Delete postmeta | |
| $wpdb->query( | |
| "DELETE FROM {$wpdb->postmeta} | |
| WHERE post_id IN ($ids_placeholder)" | |
| ); | |
| // Delete booking posts | |
| $wpdb->query( | |
| "DELETE FROM {$wpdb->posts} | |
| WHERE ID IN ($ids_placeholder)" | |
| ); | |
| return true; // More batches may still exist | |
| } | |
| /** | |
| * Deletes ALL old bookings in dynamic batch loops. | |
| */ | |
| function bkap_delete_all_old_bookings() { | |
| $batch_size = 200; // Change as needed | |
| while ( bkap_delete_old_booking_batch( $batch_size ) ) { | |
| // Continue deleting until false is returned | |
| error_log( "BKAP Cleanup: Batch deleted, checking next..." ); | |
| } | |
| error_log( "BKAP Cleanup: Completed — all old bookings removed." ); | |
| } | |
| add_action( 'init', function() { | |
| if ( isset( $_GET['run_bkap_cleanup'] ) ) { | |
| bkap_delete_all_old_bookings(); | |
| wp_die( 'Booking cleanup completed successfully.' ); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment