Wordpress - WordPress is stripping escape backslashes from JSON strings in post_meta

There is an elegant way to handle this!

Pass the JSON encoded string through wp_slash(). That function will escape the leading slash of each encoded unicode character, which will prevent update_metadata() from stripping them.


Doesn't look like there's any way to avoid it.

The update_metadata() function, which is ultimately responsible for saving the meta, explicitly runs a stripslashes_deep() on the meta value. This function will even strip slashes from array elements, if the value were an array.

Theres a filter that's run AFTER that called sanitize_meta, which you could hook in to. But at that point, your slashes have already been stripped, so you can't reliably determine where they needed to be added back in (or at least, I don't know how you would tell the difference between quoting legitimate JSON delimiters vs bits of values).

Can't speak to why it does this, but it does. Probably because it's eventually run through wpdb->update, which needs the strings unescaped.

As you feared, you're probably better off just storing the value as an array, which'll get serialized (as you said). If you want it as JSON later, you can just run it through json_encode().


You can cheat to wordpress with something like this:

$cleandata = str_replace('\\', '\\\\', json_encode($customfield_data, true));

This is that easy *elegant solution*...

Tags:

Json

Post Meta