0

I'm currently developing a bus route planner, using Wordpress as my CMS. I've added some JQuery code to add support for ajax (so visitors can use the route planner and load the route without having to go to another page), but it's not working.

On closer inspection using Chrome's Inspect Element, Wordpress appears to be adding paragraphs to the Javascript code, although the Javascript code is properly configured and is recognised as such:

enter image description here

Another member on the project also has the same issue:

enter image description here

Why is Wordpress doing this, and how can I stop Wordpress from adding paragraphs to the code? I am adding the code through the raw text editor for the page, so it's not like I'm adding the code via the Visual mode.

2
  • 1
    Definitely agree with DrewAPicture. If you really want to do it from the WP admin you can try something like this: wordpress.org/plugins/style-buddy - Note that this is a plugin I created for more quickly modifying js on client sites (without having to access FTP every time) Commented Sep 21, 2014 at 23:03
  • There are huge security risks to putting javascript code inside a posts content, that's not the way to do it, especially if you're a developer with access to the code
    – Tom J Nowell
    Commented Sep 21, 2014 at 23:07

2 Answers 2

4

The post editor is really not meant for inserting functional code like JavaScript into the page.

Anything you put through the post editor will get run through wpautop() before output, which is what adds the paragraph tags -- even if you enter it via the Text mode. I'd suggest outputting your JavaScript via a hook on the page instead of via the post editor.

Something like this:

/**
 * Output JS to the page head.
 */
function output_head_js() {
    ?>
    <script type=“text/javascript”>
        $( ‘#gosearch’ ).click( function() {
        …
    });
    </script>
    <?php
}
add_action( 'wp_head', 'output_head_js' );
1

You could also remove all the breaks in your code. For example of:

Instead of:

function() doSomething() {
//code goes here
}

Do something like this:

function() doSomething() {//code goes here}

Its annoying but it will allow you to still use WordPress' text editor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.