I have a custom post type article and custom fields article_keywords which I have created using the ACF plugin https://www.advancedcustomfields.com/, as there were many articles present we were trying to upload the articles through CSV. As all the contents were present in simplified chinese , many posts custom fields were not able to update. We have convert the CSV file from the Microsoft Excel and google sheet as well. Only some of the contents we were able to update.
I have the below function for CSV upload in wordpress. I am not able to get which post I am not able to update as update_post_meta($post_id, $key, $value)
is not null always even if the post is updated.
I am attaching a article csv file link in the below as well as the code used for import.
https://docs.google.com/spreadsheets/d/1w9QVwls6v05VqzUfhZ1k27ljAGn-koRXp1cJN86Aufs/edit?usp=sharing
function import_custom_posts_from_csv($file_path)
{
if (!file_exists($file_path) || !is_readable($file_path)) {
return false;
}
$header = null;
$data = array();
if (($handle = fopen($file_path, 'r')) !== false) {
while (($row = fgetcsv($handle, 1000, ',')) !== false) {
if (!$header) {
$header = $row;
} else {
// Check if the number of columns matches
if (count($header) == count($row)) {
$data[] = array_combine($header, $row);
} else {
if (count($row) > 10) {
for ($i = 0; $i < count($header); $i++) {
if (!isset($row[$i]) || $row[$i] === '') {
$row[$i] = ' '; // Replace empty columns with a space
}
}
$data[] = array_combine($header, $row);
}
}
}
}
fclose($handle);
}
foreach ($data as $row) {
// Check if the post already exists
$existing_post = get_page_by_title($row['post_title'], ARRAY_N, 'articles');
if (!empty($existing_post)) {
$post_id = $existing_post[0];
$post_data = array(
'ID' => $post_id,
'post_title' => $row['post_title'],
'post_content' => '', // Add content if you have in CSV
'post_status' => 'publish',
'post_date' => format_post_date($row['publication_date']),
);
wp_update_post($post_data);
} else {
$post_data = array(
'post_title' => $row['post_title'],
'post_content' => '', // Add content if you have in CSV
'post_status' => 'publish',
'post_type' => 'articles', // Change to your custom post type
'post_date' => format_post_date($row['publication_date']),
);
$post_id = wp_insert_post($post_data);
}
if ($post_id) {
// Add or update custom fields
foreach ($row as $key => $value) {
if ($key != 'post_title' && $key != 'publish_date') {
// Retrieve the ACF field object using the field name
$field_object = acf_get_field($key);
if ($field_object) {
$field_key = $field_object['key'];
update_post_meta($post_id, '_' . $key, $field_key);
if ($field_object['type'] == 'checkbox') {
// Split the checkbox values
$checkbox_values = explode(',', $value);
update_post_meta($post_id, $key, $checkbox_values);
} else {
update_post_meta($post_id, $key, $value);
}
}
}
}
}
}
echo '<div class="notice notice-success is-dismissible"><p>CSV file imported successfully.</p></div>';
}
3