Support » Fixing WordPress » insert a script in a post

  • Resolved antr


    I need to insert a javascript in a post.
    However, even if I write it in html format, when saving WP converts the <script>…</script> into <p><script>…</script></p> and so the javascript is not recognized as a script.
    I could make a template ad hoc but in the template hierarchy scheme
    there is only one template: single.php and I cannot discriminate between posts.
    So far, I have created a page, since pages accept ad hoc templates with their current name, but they haven’t tags and categories, so I don’t like the solution too much.
    Is there any way to insert a script in a post, or to make and activate a specific template for a post accepting javascript?

Viewing 4 replies - 1 through 4 (of 4 total)
  • You have to add js to a template file. You can add it to single.php and limit it to a specific post using a conditional.

    create a function in your functions.php file, for example:

    <?php function script_to_post(){
    $content = get_the_content();
    $postOutput = $content;
    $postOutput = preg_replace('/<p><script>/', '<script>' ,$postOutput);
    $postOutput = preg_replace('/<\/script><\/p>/', '<\/script>',$postOutput);
    echo $postOutput;
    } ?>

    call script_to_post() (or whatever you want to call it) in your loop instead of the_content();

    This function will strip the <p></p> tags from any <script></script> tags!

    Thanks, solved loading an external script file with
    <script type=”text/javascript” src=”MyScriptFile”></script>
    and then calling a function with another
    </script type=”text/javascript”>MyFunction();</script>
    WP inserts two
    in the post where I have added these two lines but it is an acceptable drawback.

    The ditor eaten two *br* tag in the last sentence. Nevertheless I hope it is understandable.
    Many thanks also to Richard for his suggestion which I have read only two minutes ago.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘insert a script in a post’ is closed to new replies.