When I use the update_post_meta() function to change a value of a key:
- when it's a normal string it works
- but when the string is the same as a JSON file it appends some extra string.
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_filesvariable is a serialized array -not a "JSON file"- andupdate_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_filesa 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:Result: