Skip to content

Instantly share code, notes, and snippets.

@trvswgnr
Created May 4, 2021 00:43
Show Gist options
  • Save trvswgnr/00703be4a5f9601e9b720030b299b4a7 to your computer and use it in GitHub Desktop.
Save trvswgnr/00703be4a5f9601e9b720030b299b4a7 to your computer and use it in GitHub Desktop.
Import a CSV into a repeater field with ACF, removing all duplicates and leaving the last entry.
<?php
/**
* Optionally import Press articles from CSV ACF
*
* @author Travis Aaron Wagner <[email protected]>
* @return void
*/
function taxa_import_press_articles_csv() {
$csv = get_field('articles_csv');
if (!$csv) return;
$csv = (string) $csv;
$existing_articles = (array) get_field('articles');
$csv_obj = get_field_object('articles_csv');
$articles_obj = get_field_object('articles');
$new_articles = array();
$row = 0;
if (($handle = fopen($csv, "r")) !== false) {
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$row++;
if ($row === 1) continue;
$new_articles[] = array(
'title' => isset($data[0]) ? $data[0] : '',
'publication' => isset($data[1]) ? $data[1] : '',
'link' => isset($data[2]) ? $data[2] : '',
);
}
fclose($handle);
}
// combine the existing and new articles, removing any exact duplicates
$combined_articles = array_unique(array_merge($existing_articles, $new_articles), SORT_REGULAR);
// check for articles with the same title and publication & store their index
$duplicates = array();
foreach ($combined_articles as $i => $article) {
@$duplicates[$article['title'] . $article['publication']][] = $i;
}
// remove entries with the same title and publication, keeping the latest entry
foreach ($duplicates as $duplicate) {
if (count($duplicate) > 1) { // if duplicates exist
$d = array_slice($duplicate, 0, -1);
foreach ($d as $index) { // for every duplicate
unset($combined_articles[$index]); // remove the index
}
}
}
$updated_articles = array_values($combined_articles); // reset array index
// replace articles repeater with CSV values
update_field($articles_obj['key'], $updated_articles);
// clear csv upload field
update_field($csv_obj['key'], '');
}
add_action( 'save_post', 'taxa_import_press_articles_csv', 10 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment