I’m working on creating an import script to migrate data from an Excel spreadsheet that a client is providing, and converting each row into a WordPress post. So far, I’ve got the posts being created and all custom fields being filled in properly…except for one.
One of the fields is Associated Parts. I’d like to use the Post Object for this field, but I can’t seem to find any documentation on the formatting to use in order to assign a post object (or preferably multiple objects) to this field’s value via my PHP script.
The following is an example of some code that I’m using to populate the “specifications” repeater field that has two sub fields, label and value.
$field_key = 'field_53ef95cead820';
$value = get_field($field_key, $postID);
foreach($specs as $spec):
$specArray = explode(':',$spec);
if($specArray[0] && $specArray[1]):
$value[] = array("label" => $specArray[0], "value" => $specArray[1]);
endif;
++$i;
endforeach;
update_field( $field_key, $value, $postID );
To modify the associated parts field, should I set it up as a repeater like this and then create some sort of array to populate it, or should I use the multi select option and still pass some sort of an array to it. I’m happy to go either route, I just need some way to get those fields in there.
It’s impossible to add associate products (other posts) during the initial import due to the fact that while you are importing the first product into WordPress, it’s associated parts have not yet been created. For this reason I had to run two imports of the spreadsheet into WordPress.
On the first import, it created all the posts and added all of the non-relational custom fields as they appeared in the spreadsheet. I setup the script the print the post ID’s of the imported products in a table format that allowed me to easily copy and paste all of the ID’s at once from the script output back into a “Product ID” field in the spreadsheet. The script checks for the existence of a product ID and this field is what will determine if it is creating a new post/product or updating an existing one.
Once all the products had been imported and their respect ID’s were added to the spreadsheet, we began the second import. We used the exact same spreadsheet with the only difference being that now it had the WordPress ID’s added to a column.
Breakdown of the code line by line:
I had to guess as to the format I needed to use for the value of the field. At first, I tried passing in an array of Post Objects and that didn’t work. In the WordPress post editor, I inspected the code and saw that the value of their input field (when another post was selected) was that posts ID. After switching to a numeric array containing the Posts’ ID’s, the update_field() function accepted them perfectly without incident.
We’re done.