When I use the update_post_meta() function to change a value of a key:
For example, when I save this string:
a:1:{i:1;a:6:{s:5:"index";s:1:"0";s:13:"attachment_id";s:1:"0";s:14:"thumbnail_size";s:0:"";s:4:"name";s:3:"aaa";s:4:"file";s:3:"aaa";s:9:"condition";s:3:"all";}}
It is saved on the wp_postmeta table as:
s:162;"a:1:{i:1;a:6:{s:5:"index";s:1:"0";s:13:"attachment_id";s:1:"0";s:14:"thumbnail_size";s:0:"";s:4:"name";s:3:"aaa";s:4:"file";s:3:"aaa";s:9:"condition";s:3:"all";}}"
When I use a short string there are no problems. How can solve this?
My code:
$edd_files='a:1:{i:1;a:6:{s:5:"index";s:1:"0";s:13:"attachment_id";s:1:"0";s:14:"thumbnail_size";s:0:"";s:4:"name";s:3:"aaa";s:4:"file";s:3:"aaa";s:9:"condition";s:3:"all";}}';
update_post_meta($download_id,'edd_download_files',$edd_files);
The reason why this is happening is because update_post_meta()
serializes the value you pass as third parameter (see update_metadata()).
Your $edd_files
variable is a serialized array -not a "JSON file"- and update_post_meta()
is serializing it again before saving it to the database, hence the reason why your serialized string changed like that.
I don't know why you're assigning $edd_files
a serialized string but you can convert it back to an array using the maybe_unserialize() function before saving it as a post meta and then the value will be saved on the database as a serialized string as expected:
$edd_files = 'a:1:{i:1;a:6:{s:5:"index";s:1:"0";s:13:"attachment_id";s:1:"0";s:14:"thumbnail_size";s:0:"";s:4:"name";s:3:"aaa";s:4:"file";s:3:"aaa";s:9:"condition";s:3:"all";}}';
// Convert serialized string back into an array
$edd_files = maybe_unserialize($edd_files);
update_post_meta($download_id, 'edd_download_files', $edd_files);
Result: