Deleting Event When Re-Importing
The Events Aggregator by Modern Tribe has limitations. One of them is that it will not detect when an event is deleted from an external calendar. The result is that you have to go in and delete them yourself, if you know about them.
This code snippet is one way to solve it, but it also has it’s limitations. Basically, you will set it up for one calendar to be imported into it’s own Event Category. This snippet will basically delete all the events within the category and create new events based on the events that were imported.
To protect an event from being deleted, all you need to do is remove the event from the category.
Here’s the code:
<?php | |
/** | |
* Description: Delete and re-import events within a certain category | |
* | |
* Usage: copy the snippet in your active (child) theme's functions.php file | |
* | |
* Plugins: Events Aggregator | |
* Author: Mike Cotton | |
* Last updated: April 25, 2019 | |
*/ | |
class NMSA_EC_ImportFixer { | |
const VERSION = '0.0.3'; | |
public function __construct() { | |
add_action('init', array($this, 'init')); | |
} | |
public function init() { | |
add_action('tribe_aggregator_after_insert_post', array($this, 'handle_after_insert_post'), 10, 3); | |
} | |
public function handle_after_insert_post($event, $item, $record) { | |
$record_meta = $record->meta; | |
$this_category_term_id = Tribe__Utils__Array::get($record_meta, 'category', false); | |
if (empty($this_category_term_id)) { | |
return; | |
} | |
$import_ids = $this->get_import_ids($record_meta); | |
if (!$import_ids) { | |
return; | |
} | |
$relevant_existing_events = tribe_get_events([ | |
'fields' => 'ids', | |
'start_date' => date('Y-m-d H:i:s', time()), // starting now or later | |
'tax_query' => [ | |
[ | |
'taxonomy' => Tribe__Events__Main::TAXONOMY, | |
'field' => 'term_id', | |
'terms' => [$this_category_term_id], | |
'operator' => 'IN' | |
] | |
], | |
'meta_key' => '_uid', | |
'meta_value' => $import_ids, | |
'meta_compare' => 'NOT IN' | |
]); | |
foreach ($relevant_existing_events as $event_id) { | |
wp_delete_post($event_id, true); | |
} | |
} | |
private function get_import_ids($record_meta) { | |
$queue = Tribe__Utils__Array::get($record_meta, 'queue', false); | |
if (empty($queue) || !is_array($queue)) { | |
return false; | |
} | |
$ids = []; | |
foreach ($queue as $q) { | |
$ids[] = $q->uid; | |
} | |
return implode(",", $ids); | |
} | |
} | |
new NMSA_EC_ImportFixer(); |
Share this:
- Click to email a link to a friend (Opens in new window)
- Click to print (Opens in new window)
- Click to share on Facebook (Opens in new window)
- Click to share on Twitter (Opens in new window)
- Click to share on Reddit (Opens in new window)
- Click to share on Pinterest (Opens in new window)
- Click to share on LinkedIn (Opens in new window)
Mike
Owner of Cotton Web Services and this particular blog. Also one of team members at Holy Fire Games and Modern Tribe. @codingmusician on Twitter