Correct way to insert serialized data into WordPress Post Meta using update_post_meta

2.1k Views Asked by At

I am trying to insert serialized data into the wp_postmeta table using the update_post_meta function.

However when I insert the data into the table, it is being changed. For example, here is what I am trying to insert:

update_post_meta($feed_id, 'wprss_ftp_taxonomies', 'a:3:{i:0;a:6:{s:8:"taxonomy";s:6:"source";s:5:"terms";a:1:{i:0;s:3:"'.$source_slug.'";}s:4:"auto";s:5:"false";s:14:"filter_subject";s:0:"";s:15:"filter_keywords";s:0:"";s:28:"post_taxonomy_compare_method";s:3:"all";}i:1;a:6:{s:8:"taxonomy";s:5:"topic";s:5:"terms";s:0:"";s:4:"auto";s:4:"true";s:14:"filter_subject";s:0:"";s:15:"filter_keywords";s:0:"";s:28:"post_taxonomy_compare_method";s:3:"all";}i:2;a:6:{s:8:"taxonomy";s:10:"categories";s:5:"terms";s:0:"";s:4:"auto";s:5:"false";s:14:"filter_subject";s:0:"";s:15:"filter_keywords";s:0:"";s:28:"post_taxonomy_compare_method";s:3:"all";}}');

So my serialized data is this:

a:3:{i:0;a:6:{s:8:"taxonomy";s:6:"source";s:5:"terms";a:1:{i:0;s:3:"'.$source_slug.'";}s:4:"auto";s:5:"false";s:14:"filter_subject";s:0:"";s:15:"filter_keywords";s:0:"";s:28:"post_taxonomy_compare_method";s:3:"all";}i:1;a:6:{s:8:"taxonomy";s:5:"topic";s:5:"terms";s:0:"";s:4:"auto";s:4:"true";s:14:"filter_subject";s:0:"";s:15:"filter_keywords";s:0:"";s:28:"post_taxonomy_compare_method";s:3:"all";}i:2;a:6:{s:8:"taxonomy";s:10:"categories";s:5:"terms";s:0:"";s:4:"auto";s:5:"false";s:14:"filter_subject";s:0:"";s:15:"filter_keywords";s:0:"";s:28:"post_taxonomy_compare_method";s:3:"all";}}

However its being inserted into the database as this:

s:577:"a:3:{i:0;a:6:{s:8:"taxonomy";s:6:"source";s:5:"terms";a:1:{i:0;s:3:"abc";}s:4:"auto";s:5:"false";s:14:"filter_subject";s:0:"";s:15:"filter_keywords";s:0:"";s:28:"post_taxonomy_compare_method";s:3:"all";}i:1;a:6:{s:8:"taxonomy";s:5:"topic";s:5:"terms";s:0:"";s:4:"auto";s:4:"true";s:14:"filter_subject";s:0:"";s:15:"filter_keywords";s:0:"";s:28:"post_taxonomy_compare_method";s:3:"all";}i:2;a:6:{s:8:"taxonomy";s:10:"categories";s:5:"terms";s:0:"";s:4:"auto";s:5:"false";s:14:"filter_subject";s:0:"";s:15:"filter_keywords";s:0:"";s:28:"post_taxonomy_compare_method";s:3:"all";}}";

It looks like its inserting it as a string, rather than just setting the value to the raw serialized data I have input.

I have no idea how to rectify this as i do not work with serialized data directly very often.

Any insight would be appreciated.

2

There are 2 best solutions below

1
On BEST ANSWER

You can "unserialize" and this will work correctly

$data   =    unserialize( 'YOUR_CODE_SERIALIZED_HERE' );
update_post_meta($feed_id, 'wprss_ftp_taxonomies', $data);
0
On

Don't serialize the array. Directly assign it to update_post_meta as an array. I just fixed my own problem here -> Why is there a string saved in my serialized array?