ACF – Import Repeater Field Values from CSV Programmatically

This is an english-only post. For people who can not read chinese, my blog is only available in chinese as I do not want to translate every single blog post... However as I was struggling the ACF & CSV import solution for over 2 weeks and finally found an easy way to do it. I felt like I should share to the world, so I wrote this article.

Why import the data programmatically

I normally helped my clients initializing the first draft of website content (not all) in Wordpress. Throughout the content implementation, I can fix the bugs and test the user experience of the backend interface. For my new project, there were 130 stores that I need to implement into the ACF (Advanced Custom Fields) repeater fields and it was a nightmare for me, and for the clients. Throughout the Internet and ACF Forum, I can only see the solutions of using importer plugins. I have tried the 3rd party plugin like WP All Import and other import plugins but they are not friendly to repeater fields. you have to store multiple repeater field values into one single column which is a pain. What I really want is to have a "CSV Import Button" next to the repeater field where you can do everything within the existing repeater field but there is none..

Steps

The ACF API provides a way to update the sub field value: update_sub_field(). We are going to parse the CSV file, update each one of the sub field in php:
  1. Prepare your CSV file with columns matched to the repeater sub fields
  2. ACF - create a csv file select field
  3. ACF - set up the repeater field with sub fields
  4. create a new post
  5. From the post, upload your csv
  6. create empty repeater fields depending on the number of rows you have in csv
  7. In the front page, paste this php code:
<?php
if(get_field('csv_file'))
{
  // load csv with SERVER PATH instead of URL
  $csv = get_attached_file(get_field('csv_file')['id']); 
  if(($handle = fopen($csv, "r")) !== FALSE)
  {
    $count=0;
    while(($data = fgetcsv($handle, 1000, ",")) !== FALSE)
    {
      // $count = acf row, $data[0] = csv column 1 value
      update_sub_field(array('repeater_name', $count, 'name'), $data[0]);
      update_sub_field(array('repeater_name', $count, 'address'), $data[1]);
      update_sub_field(array('repeater_name', $count, 'phone'), $data[2]);
      $count++;
    }
    fclose($handle);
  }
}
?>
you would have to modify the code where the fields you want to update, run the code, and you should see the data saved in the repeater of your post.
本文由 Felicoz https://felicoz.com/ 原创发布,转载请保留地址!
ACF php wordpress