Sync Bookings on Entry Trash/Restore

🧪

Experimental Snippet

This snippet was discovered in the wizard’s chaotic laboratory — an unpolished experiment, conjured to solve a niche challenge. Use at your own risk.

Deletes bookings when an entry is trashed and recreates them when restored. If a time slot has since been booked by another entry, recreation will be skipped and logged to avoid conflicts.

Instructions

See “Where do I put snippets?” in our documentation for installation instructions.

Code

Filename: gpb-sync-bookings-on-entry-trash-restore.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
/**
 * Gravity Perks // Bookings // Sync Bookings on Entry Trash/Restore
 * https://gravitywiz.com/documentation/gravity-forms-bookings/
 *
 * Experimental Snippet 🧪
 *
 * Deletes bookings when an entry is trashed and recreates them when restored.
 * If a time slot has since been booked by another entry, recreation will be
 * skipped and logged to avoid conflicts.
 */
add_action( 'gform_update_status', function( $entry_id, $new_status, $old_status ) {

	if ( ! function_exists( 'gpb_delete_entry_bookings' ) || ! class_exists( '\GP_Bookings\Booking' ) ) {
		return;
	}

	$entry_id = (int) $entry_id;
	if ( $entry_id <= 0 ) {
		return;
	}

	$flag_key = '_gpb_bookings_deleted_on_trash';

	if ( $new_status === 'trash' && $old_status !== 'trash' ) {
		$deleted = gpb_delete_entry_bookings( $entry_id, 'Entry moved to trash' );
		if ( $deleted > 0 ) {
			gform_update_meta( $entry_id, $flag_key, 1 );
		} else {
			gform_delete_meta( $entry_id, $flag_key );
		}
		return;
	}

	if ( $old_status === 'trash' && $new_status !== 'trash' ) {
		$was_deleted = (int) gform_get_meta( $entry_id, $flag_key ) === 1;
		if ( ! $was_deleted ) {
			return;
		}

		if ( ! empty( gpb_get_entry_bookings( $entry_id ) ) ) {
			gform_delete_meta( $entry_id, $flag_key );
			return;
		}

		$entry = GFAPI::get_entry( $entry_id );
		if ( is_wp_error( $entry ) || empty( $entry ) ) {
			return;
		}

		try {
			\GP_Bookings\Booking::create_from_entry( $entry );
			gform_delete_meta( $entry_id, $flag_key );
		} catch ( \Throwable $e ) {
			if ( function_exists( 'gp_bookings' ) ) {
				gp_bookings()->log_debug( sprintf( 'Restore recreation failed for entry %d: %s', $entry_id, $e->getMessage() ) );
			}
		}
	}

}, 10, 3 );

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.