Categories
Web Development

Save My JavaScript, Another WordPress Plugin Idea

As part of my work on the Facebook Tab Manager, I wrote a little shortcode routine to prevent the WordPress rich text editor from scrambling JavaScript code, such as the widget code Facebook provides for its social plugins. Would that be useful as an independent plugin? I couldn’t seem to find another one that did this in a simple way.

[savejs]<div id=”fb-root”></div><script src=”http://connect.facebook.net/en_US/all.js#appId=195268827169203&amp;xfbml=1″></script><fb:comments numposts=”10″ width=”425″ publish_feed=”true”></fb:comments>[/savejs]

The idea is that you paste your snippet of code into the Visual editor (not the HTML view). The JavaScript-powered TinyMCE editor will turn some of the characters such as the angle brackets on the tags into HTML entities as if you were pasting a code sample into your blog. At execution, the savejs Shortcode function decodes the relevant HTML entities.

It looks like this in the editor:

The savejs Shortcode

Here is the code I’m working with so far:

function savejs_shortcode($atts = NULL, $content = NULL ) {

if($content)
	{
	//check for numeric references, variants on quotation marks entities
	$content = preg_replace('/&(#8220|#8221|#8243|quot|ldquo|rdquo);/','"',$content);
	$content = preg_replace('/&(#8216|#8217|apos|lsquo|rsquo);/',"'",$content);
	//convert standard entities including <>
	$content = html_entity_decode($content);
	
	//optionally, add a surrounding div that can be styled to add margins or padding
	if($atts["style"])
		$content = '<div style="'.$atts&#91;"style"&#93;.'">'.$content.'</div>';
	}

	return $content;
}
add_shortcode('savejs', 'savejs_shortcode');

I just updated the version of this code used in Facebook Tab Manager.

Note: I have run into some odd behavior with pasting code into the visual editor. Sometimes TinyMCE will produce a duplicate copy of the code snippet, which I then have to clean up by switching to the HTML view. Not sure why this happens with some JS widgets and not others.

Leave a Reply