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>' ] ) );

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>"}"

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>"}"

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>' ] ) ) );
get_post_meta( 878, 'dumb_meta', true );
// string(67) "{"HTML Link":"<a href=\"https:\/\/derrick.blog\/\">My Blarg!<\/a>"}"

perfect cat GIF by Amanda

Leave a Reply