class-cleanup.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. class Booked_WC_Cleanup {
  3. protected $appointments = array();
  4. private function __construct() {
  5. $this->appointments_to_clean();
  6. $this->clean();
  7. }
  8. public static function start() {
  9. return new self();
  10. }
  11. protected function clean() {
  12. //booked_mailer( 'justin@boxystudio.com', 'Booked CRON Test', 'cron run', 'noreply@getbooked.io', 'Booked' );
  13. foreach ($this->appointments as $app) {
  14. $app_meta = get_post_meta($app->ID);
  15. if ( !isset($app_meta['_booked_wc_appointment_order_id']) || isset($app_meta['_booked_wc_appointment_order_id']) && !$app_meta['_booked_wc_appointment_order_id'] ):
  16. wp_delete_post($app->ID, true);
  17. endif;
  18. }
  19. }
  20. protected function appointments_to_clean() {
  21. add_action('pre_get_posts', array($this, 'pre_get_posts'));
  22. $this->appointments = get_posts(array(
  23. 'posts_per_page' => -1,
  24. 'post_type' => BOOKED_WC_POST_TYPE,
  25. 'post_status' => array('any'),
  26. 'suppress_filters' => false,
  27. '_' . BOOKED_WC_PLUGIN_PREFIX . 'cleanup' => true
  28. ));
  29. remove_action('pre_get_posts', array($this, 'pre_get_posts'));
  30. return $this;
  31. }
  32. public function pre_get_posts( $query ) {
  33. if ( !$query->get( '_' . BOOKED_WC_PLUGIN_PREFIX . 'cleanup') ) {
  34. return $query;
  35. }
  36. add_filter('posts_where', array($this, 'posts_where'));
  37. return $query;
  38. }
  39. public function posts_where( $where ) {
  40. remove_filter('posts_where', array($this, 'posts_where'));
  41. $time_created_meta_key = '_' . BOOKED_WC_PLUGIN_PREFIX . 'time_created';
  42. $custom_fields_meta_key = '_cf_meta_value';
  43. $post_type = BOOKED_WC_POST_TYPE;
  44. $mode = Booked_WC_Settings::get_option('cleanup_mode');
  45. $available_schedules = wp_get_schedules();
  46. $schedule_details = $available_schedules[$mode];
  47. $current_time = current_time('timestamp');
  48. $time_to_compare = $current_time - esc_sql($schedule_details['interval']);
  49. global $wpdb;
  50. $appointment_to_delete = "SELECT p.ID FROM {$wpdb->posts} p
  51. INNER JOIN {$wpdb->postmeta} time_created ON (p.ID = time_created.post_id AND time_created.meta_key = '{$time_created_meta_key}')
  52. INNER JOIN {$wpdb->postmeta} custom_fields ON (p.ID = custom_fields.post_id AND custom_fields.meta_key = '{$custom_fields_meta_key}')
  53. WHERE p.post_type = '{$post_type}'
  54. AND CAST(time_created.meta_value AS SIGNED) < '{$time_to_compare}'
  55. AND custom_fields.meta_value LIKE '%product_id::%'";
  56. $where .= "AND `$wpdb->posts`.`ID` IN ( {$appointment_to_delete} )";
  57. return $where;
  58. }
  59. }