Prevent escaping javascript in visual editor

I tried to put my JavaScript code directly to my blog content, but It seems WordPress escapes [ ] chars.

Input:

<p>Some content blah blah</p>

<script>
var locations = [{
    lat: 50.765688, 
    lng: 15.056265
},{
    lat: 50.765688, 
    lng: 15.056265}
];
</script>

Output:

var locations = &#091;{
  lat: 50.765688,
  lng: 15.056265,
  ...

Is there any way how to prevent escaping javascript code?

1 Answer
1

Adding scripts directly to the content is not a good idea. You can disable escaping of content, but that is even a worse idea.

Here we have a couple of solutions.

Using a plugin

The PHP Code Widget allows you to add almost anything as a widget. If you have some text widgets, you can replace them with this, while also adding your script.

Enqueuing the script

The proper way would be to enqueue them using wp_enqueue_script. To do so, save your scripts into .js file, and them enqueue them as follows:

add_action('wp_enqueue_scripts', 'enqueue_my_script');
function enqueue_my_script(){
    wp_enqueue_script('my-handle','URL-HERE');
}

You can also use a conditional such as if ( is_single() ) to make sure it’s only output on single posts.

Adding the script directly to the template

This is another method which is legitimate, but not the best practice. Simply open your single.php file and paste your script inside it. You should use <script></script> tags too.

Leave a Comment