Convert Serialized Data to WP Custom Fields

38 Views Asked by At

I have exported data from my website and intend to import it into a new template and post type. My problem is that one of the custom fields of the previous template is stored in PHP serialized form in the database. How can I convert four of its fields into a new custom field that I created with ACF?

I have tested the WP All Import plugin and the Serialize Fields option, but it didn't work.

The following is an example of serialized data from which I intend to extract address, phone number, and latitude and longitude.

a:11:{s:7:"address";s:41:"باهنر - نبش كوجه شيرازي";s:11:"gpsLatitude";s:9:"35.805457";s:12:"gpsLongitude";s:8:"51.43616";s:18:"streetViewLatitude";s:0:";s:19:"streetViewLongitude";s:0:";s:17:"streetViewHeading";s:1:"0";s:15:"streetViewPitch";s:1:"0";s:14:"streetViewZoom";s:1:"0";s:9:"telephone";s:0:";s:5:"email";s:0:";s:3:"web";s:0:";}

1

There are 1 best solutions below

0
Rao azwar On

Try this code

<?php
// Serialized data from your example
$serialized_data = 'a:11:{s:7:"address";s:41:"باهنر - نبش كوجه شيرازي";s:11:"gpsLatitude";s:9:"35.805457";s:12:"gpsLongitude";s:8:"51.43616";s:18:"streetViewLatitude";s:0:";s:19:"streetViewLongitude";s:0:";s:17:"streetViewHeading";s:1:"0";s:15:"streetViewPitch";s:1:"0";s:14:"streetViewZoom";s:1:"0";s:9:"telephone";s:0:";s:5:"email";s:0:";s:3:"web";s:0:";}';

// Unserialize the data
$unserialized_data = unserialize($serialized_data);

// Retrieve specific fields
$address = isset($unserialized_data['address']) ? $unserialized_data['address'] : '';
$latitude = isset($unserialized_data['gpsLatitude']) ? $unserialized_data['gpsLatitude'] : '';
$longitude = isset($unserialized_data['gpsLongitude']) ? $unserialized_data['gpsLongitude'] : '';
$telephone = isset($unserialized_data['telephone']) ? $unserialized_data['telephone'] : '';

// Assuming you have created custom fields using ACF with field keys like 'address_field', 'latitude_field', 'longitude_field', 'telephone_field'

// Update post meta with ACF
// Make sure to replace '123' with the post ID where you want to save the data
update_field('address_field', $address, 123);
update_field('latitude_field', $latitude, 123);
update_field('longitude_field', $longitude, 123);
update_field('telephone_field', $telephone, 123);
?>