How can I programmatically save data into custom fields that contain serialized data?

For serializing and unserializing Data in WordPress, you can use maybe_unserialize and maybe_serialize. If you want to handle the data and add/change values, you could use something like this:

$metaarray = maybe_unserialize(get_post_meta($post_id,'_ait-dir-item',TRUE));
//now $metaarray has an array, if it is serialized. If not, $metaarray has a string.
if(is_array($metaarray)){
     $metaarray['mynewfield'] = 'Some text i need to add';
     $metaarray['mysecondnewfield'] = array('an' => 'array','i' => 'need', 'to' => 'add');
}
update_post_meta($post_id,'_ait-dir-item',maybe_serialize($metaarray));

Happy Coding,
Kuchenundkakao

Leave a Comment