Automattic\WooCommerce\Internal\Logging

OrderLogsCleanupHelper::get_dangling_ordersprivateWC 1.0

Get orders with _debug_log_source meta older than the given max age.

Orders that also have _debug_log_source_pending_deletion will be handled by the batch processor, but cleaning them up here too is harmless.

Method of the class: OrderLogsCleanupHelper{}

No Hooks.

Returns

Array. Associative array of order ID => log source name.

Usage

// private - for code of main (parent) class only
$result = $this->get_dangling_orders( $max_age ): array;
$max_age(int) (required)
Maximum age in seconds.

OrderLogsCleanupHelper::get_dangling_orders() code WC 10.8.1

private function get_dangling_orders( int $max_age ): array {
	if ( ! $this->hpos_in_use && ! $this->cpt_in_use ) {
		return array();
	}

	global $wpdb;

	$cutoff_date = gmdate( 'Y-m-d H:i:s', time() - $max_age );

	$meta_table  = $this->hpos_in_use ? "{$wpdb->prefix}wc_orders_meta" : $wpdb->postmeta;
	$order_table = $this->hpos_in_use ? "{$wpdb->prefix}wc_orders" : $wpdb->posts;
	$id_column   = $this->hpos_in_use ? 'order_id' : 'post_id';
	$type_column = $this->hpos_in_use ? 'type' : 'post_type';
	$date_column = $this->hpos_in_use ? 'date_created_gmt' : 'post_date_gmt';

	// phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared
	$rows = $wpdb->get_results(
		$wpdb->prepare(
			"SELECT m.{$id_column} as order_id, m.meta_value
			 FROM {$meta_table} m
			 INNER JOIN {$order_table} o ON m.{$id_column} = o.id
			 WHERE m.meta_key = %s
			 AND o.{$type_column} = %s
			 AND o.{$date_column} < %s
			 LIMIT %d",
			'_debug_log_source',
			'shop_order',
			$cutoff_date,
			self::MAX_ORDERS_PER_RUN
		),
		ARRAY_A
	);
	// phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared

	return array_column( $rows, 'meta_value', 'order_id' );
}