WordPress Post Meta and JSON

…or how I stopped worrying and learned to love the slashes.

Post Meta in WordPress is a great tool to store random bits of data associated with your posts. But did you know that it comes with its own set of problems?

Have you ever tried storing a JSON string inside of post meta?

update_post_meta( 878, 'dumb_meta', wp_json_encode( [ 'HTML Link' => '<a href="https://derrick.blog/">My Blarg</a>' ] ) );Code language: PHP (php)

Only to find out that the JSON has been destroyed?

get_post_meta( 878, 'dumb_meta', true );
// string(61) "{"HTML Link":"<a href="https://derrick.blog/">My Blarg!</a>"}"Code language: JavaScript (javascript)

This is because WordPress passes the meta value through wp_unslash() before storing it in the database. This causes the already existing escaped/slashes data inside the JSON string to be destroyed:

wp_json_encode( [ 'HTML Link' => '<a href="https://derrick.blog/">My Blarg!</a>' ] );
// string(67) "{"HTML Link":"<a href=\"https:\/\/derrick.blog\/\">My Blarg!<\/a>"}"Code language: HTML, XML (xml)

Luckily, there’s a quick solution to this. You can pass your data through wp_slash() to double-encode it, so that when wp_unslash() does its job, it only unslashes a single iteration of slashes, leaving your JSON string safe:

update_post_meta( 878, 'dumb_meta', wp_slash( wp_json_encode( [ 'HTML Link' => '<a href="https://derrick.blog/">My Blarg!</a>' ] ) ) );Code language: PHP (php)
get_post_meta( 878, 'dumb_meta', true );
// string(67) "{"HTML Link":"<a href=\"https:\/\/derrick.blog\/\">My Blarg!<\/a>"}"Code language: JavaScript (javascript)

perfect cat GIF by Amanda

Other Posts Not Worth Reading

Hey, You!

Like this kind of garbage? Subscribe for more! I post like once a month or so, unless I found something interesting to write about.


Comments

Leave a Reply