WordPress Single Quote JSON Issue

In a WordPress shortcode function, I have the following:

$args=shortcode_atts( array(
   'setting1' => 'value1',
   'setting2' => 'value2'
), $atts);


return '<div data-myData='{' . json_encode( $args ) . '}' ></div>';

I’m trying to retrieve the arguments and return a string of HTML. That html should look like:

Read More
<div data-myData='{ "setting1" : "value1" , "setting2" : "value2" }'></div>

Then some JS picks it up from there.
However, it seems that however I approach this, WP keeps converting my single quotes to double quotes on the data-myData attribute and I wind up with this:

<div data-myData="{ "setting1" : "value1" , "setting2" : "value2" }"></div>

Is there something simple I’m missing here?
Thanks!

Related posts

Leave a Reply

1 comment

  1. You’re inserting JSON into an html context, so you need to use HTML-specific quoting methods:

    return '<div data-myData="' . htmlspecialchars(json_encode( $args )) . '"></div>';
                                  ^^^^^^^^^^^^^^^^