WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How to allow javascript in posts? (6 posts)

  1. MC
    Member
    Posted 1 year ago #

    I have a trip advisor badge I am trying to put up on a site. It uses javascript similar to this:
    <script src="http://www.jscache.com/variables.123"></script>

    I found a few closed threads on this but couldn't quite figure out how one would go about keeping the editor from stripping the tag out as it seems to disappear when you update the post.

  2. Something similar to this came up a few days ago.

    http://wordpress.org/support/topic/adding-a-geotrust-malware-seal-to-a-wordpress-website?replies=9#post-3424674

    Adding raw javascript to a post or page is always tricky. It may be easier to can create a shortcode plugin and use that shortcode in the place of that script.

    <?php
    /*
    Plugin Name: Trip Advisor Badge Shortcode
    Description: Use [mh-tripadvisor] to insert a trip advisor badge into your post or page.
    Author: Jan Dembowski
    Version: 0.1
    */
    
    add_shortcode( 'mh-tripadvisor', 'mh_trip_script' );
    function mh_trip_script( $atts ) {
    	$mh_text = '<script src="http://www.jscache.com/variables.123"></script>';
    	return $mh_text;
    }

    Shortcodes are cool. ;)

  3. MC
    Member
    Posted 1 year ago #

    Very cool trick. I was thinking of putting it in a conditional tag in the header of the theme but is a more portable solution.

    Ideally it would be nice just to tell the parser not to strip the script tag out of the editor area. I saw this suggestion on another site, saying to put this in the functions.php but I tried it in my twentytwelve child theme and it didn't appear to have any effect on the situation:

    global $allowedposttags;
     $allowedposttags['script'] = array(
         'type' => array(),
         'src' => array()
     );

    from http://stackoverflow.com/questions/3024545/wordpress-extended-valid-elements-for-script-tag

  4. MC
    Member
    Posted 1 year ago #

    I followed up on your suggestion and it works! I ended up putting the html code and snippet in the shortcode (may try and put it in a widget instead of in a post at some point). That was fun, it was the first time I worked with anything custom in the plugins folder!

    For future reference, if a reader wants to implement a similar solution here is a summary of how to go about this:

    Save the code snippet in a file ( I called this file tripadvisor-icon.php ) in the root of your plugins folder.

    Enable the plugin (it should show up in the list of installed)

    Insert shortcode in your post : )

  5. I followed up on your suggestion and it works!

    See how easy that was? Glad to help. ;)

  6. MC
    Member
    Posted 1 year ago #

    I am really excited about what I learned! today is off to a great start. thank you very much!

Topic Closed

This topic has been closed to new replies.

About this Topic