I have a function (see in full below) that syncs data into WP from an external database. It's a list of scheduled items. When the schedule is updated, old data should be deleted. See this snippet:
$wpdb->delete(
$table,
array(
'schedule_item_id' => $item->id
)
)
But this is not happening. For example if I have an item "A" scheduled on a Tuesday at 6pm, then I remove that from the external database and I replace it with ietm "B" scheduled at the same time. WordPress should delete item "A", but it doesn't. I see both items "A" and "B" on the schedule. $wpdb->delete is not removing it. Am I doing something wrong here? Here's the complete function:
function sync_schedule($scheduleItems) {
global $wpdb;
foreach($scheduleItems as $item) {
if (!$item->show) { continue; }
$table = $wpdb->prefix . 'schedule_items';
$existing_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE schedule_item_id=%d", $item->id));
$show = get_show_post_by_id($item->show);
if (!$show) { continue; }
if (empty($existing_row) && $item->deleted == FALSE) {
$wpdb->insert(
$table,
array(
'run_date_time' => $item->runDateTime,
'show_id' => $item->show,
'show_title' => $show->post_title,
'show_post_id' => $show->ID,
'channel_id' => $item->channel,
'channel_post_id' => 0,
'schedule_item_id' => $item->id
)
);
} else if ($item->deleted == FALSE){
$wpdb->update(
$table,
array(
'run_date_time' => $item->runDateTime,
'show_id' => $item->show,
'show_title' => $show->post_title,
'show_post_id' => $show->ID,
'channel_id' => $item->channel,
'channel_post_id' => 99,
'schedule_item_id' => $item->id
),
array(
'schedule_item_id' => $item->id
)
);
} else {
$wpdb->delete(
$table,
array(
'schedule_item_id' => $item->id
)
);
}
}
}