Created
March 13, 2025 16:17
-
-
Save andrasguseo/ff512b2253ff51fcb02aeded29d8fe76 to your computer and use it in GitHub Desktop.
ET > Delete abandoned orders and related tickets (experimental)
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 | |
/** | |
* Deletes Tickets Commerce Orders and related Tickets/Attendees, | |
* which are missing a related event or post. | |
* Creating a database dump before and running a test on a staging site first is recommended. | |
* | |
* Usage: Add the snippet with Code Snippets as a "run once" snippet. | |
* Run the snippet when needed. | |
* | |
* @author: Andras Guseo | |
* | |
* Plugins required: Event Tickets | |
* | |
* @since March 13, 2025 Initial version. | |
*/ | |
add_action( 'init', function () { | |
error_log( 'Start cleaning abandoned orders.' ); | |
// Bail if not admin. | |
if ( ! is_admin() ) { | |
error_log( 'not admin' ); | |
return; | |
} | |
global $wpdb; | |
// Get the abandoned orders - orders without a related event. | |
error_log( 'Getting abandoned orders' ); | |
$abandoned_orders = $wpdb->get_col( | |
"SELECT pm.post_id FROM {$wpdb->postmeta} AS pm | |
LEFT JOIN {$wpdb->posts} AS p ON pm.meta_value = p.ID | |
WHERE pm.meta_key = '_tec_tc_order_events_in_order' | |
AND p.ID IS NULL" | |
); | |
if ( empty( $abandoned_orders ) ) { | |
error_log( 'No abandoned orders found.' ); | |
return; | |
} | |
$related_tickets = []; | |
// Get the related ticket post IDs for each abandoned order. | |
foreach ( $abandoned_orders as $order_id ) { | |
error_log( 'Getting tickets for order ' . $order_id ); | |
$tickets = $wpdb->get_col( | |
$wpdb->prepare( | |
"SELECT meta_value FROM {$wpdb->postmeta} | |
WHERE post_id = %d AND meta_key = '_some_ticket_meta_key'", | |
$order_id | |
) | |
); | |
if ( ! empty( $tickets ) ) { | |
error_log( 'Adding tickets to the array.' ); | |
$related_tickets = array_merge( $related_tickets, $tickets ); | |
} | |
} | |
// Merge orders and related tickets into a single array. | |
$posts_to_delete = array_merge( $abandoned_orders, $related_tickets ); | |
error_log( 'Starting to delete posts.' ); | |
if ( ! empty( $posts_to_delete ) ) { | |
foreach ( $posts_to_delete as $post_id ) { | |
if ( wp_delete_post( $post_id, true ) ) { | |
error_log( 'Deleted ' . $post_id ); | |
} else { | |
error_log( 'Deleting ' . $post_id . ' failed.' ); | |
} | |
} | |
} | |
error_log( 'Finished cleaning abandoned orders and related tickets.' ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment