This must be fairly simple :) I'm trying to import data into ACF repeater fields and am mostly following the answer to Add special meta box to custom post type
But what I have below isn't saving the data to the ACF fields. The uploaded CSV file is saved to /uploads/, the page Ajax saves on Update, but no data is written to the ACF fields.
My ACF field IDs are correct. The CSV file format is
2023 Winner,https://example.com/
I'm not using a Custom Post Type as in the linked answer; I'm using a page, and the meta box shows up on all pages, but that shouldn't matter, or does it? I have ACF set to show the metafields on the page template for the page I'm using.
No debug.log errors. Using WP 6.2.2 and PHP7.4. ACF Pro 6.2.0.
Is the issue that the $post_ID isn't being passed?
function add_custom_meta_box_acf()
{
add_meta_box(
'custom_meta_box_acf', // $id
'Import ACF Repeater Data', // $title
'show_custom_meta_box_acf', // $callback
'page', // $page
'side', // $context
'high' // $priority
);
}
add_action('add_meta_boxes', 'add_custom_meta_box_acf');
function show_custom_meta_box_acf()
{
global $post;
wp_nonce_field(basename(__FILE__), 'wpse_our_nonce');
?>
<p>Upload CSV File to import repeater field data</p>
<input type="file" name="import_repeater_data" value="">
<?php
}
function update_edit_form() {
echo ' enctype="multipart/form-data"';
}
add_action('post_edit_form_tag', 'update_edit_form');
function acf_add_meta_data($post_id)
{
// verify nonce
if (!isset($_POST['wpse_our_nonce']) || !wp_verify_nonce($_POST['wpse_our_nonce'], basename(__FILE__)))
return 'nonce not verified';
// check autosave
if (wp_is_post_autosave($post_id))
return 'autosave';
//check post revision
if (wp_is_post_revision($post_id))
return 'revision';
// check permissions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id))
return 'cannot edit page';
} elseif (!current_user_can('edit_post', $post_id)) {
return 'cannot edit post';
}
if (!empty($_FILES['import_repeater_data']['name'])) {
$upload = wp_upload_bits($_FILES['import_repeater_data']['name'], null, file_get_contents($_FILES['import_repeater_data']['tmp_name']));
$file = fopen($upload['url'], 'r');
$i = 0;
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
update_post_meta($post_id, 'winners_page_repeater_' . $i . '_winner_year_and_award', $line[0] );
update_post_meta($post_id, '_winners_page_repeater_'. $i . '_winner_year_and_award', 'field_64de8204ab7c2');
update_post_meta($post_id, 'winners_page_repeater_' . $i . '_award_year_link', $line[1] );
update_post_meta($post_id, '_winners_page_repeater_'. $i . '_award_year_link', 'field_64de7fb2f2a2e');
$i++;
}
fclose($file);
update_post_meta($post_id, 'winners_page_repeater', $i);
update_post_meta($post_id, '_winners_page_repeater_', 'field_64de7cf91c48f');
} else {
echo 'empty file';
}
}
add_action('save_post', 'acf_add_meta_data');
add_action('new_to_publish', 'acf_add_meta_data');