I noticed that WordPress these days uses a shortcode to define image captions, of the form:
[caption id="" align="aligncenter" width="630" caption="Image title goes here"]<img src="http://domain.com/imgpath/../image.jpg" width="630" height="420" />[/caption]
I’ve recently redone our blog template at [Technomadics](http://technomadics.net), and while setting up the new preview template in MarsEdit, thought I’d take a stab at implementing support for captions, too, via some javascript in the template.
I was successful! Here’s how I did it:
Added the following to the “head” section:
<script type="text/javascript"> var prior_content; function watch_for_changes() { var check = function() { var elt = document.getElementById('content'); if ( elt.innerHTML != prior_content ) { elt.innerHTML = apply_filters(elt.innerHTML); prior_content = elt.innerHTML; } setTimeout(check, 100); }; setTimeout(check, 100); } function apply_shortcode(source, name, callback) { return source.replace(new RegExp('\\[' + name + '\\s*([^\\]]*)\\]((.|[\s\n])*?)\\[/' + name + '\\]', 'g'), function(match, paramString, content) { params = new Object(); reg = /([a-z]+)="((:?="[^"]+"|[^"])*)"/gi; while ( (match = reg.exec(paramString)) != null ) { params[match[1]] = match[2]; } return callback(params, content); }); } function apply_filters(html) { html = apply_shortcode(html, "caption", function(args, content) { return '<div '+ 'class="wp-caption ' + (typeof(args.align) != 'undefined' ? args.align : '') + '" '+ 'style="width: ' + args.width + 'px;">' + content + '<p class="wp-caption-text">' + args.caption + '</p></div>'; }); return html; } </script> |
…changed to ‘body’ tag to…
<body onload="watch_for_changes();"> |
…And wrapped a div around the main “#body#, #extended#” content with an id
of content
:
<div id="content"> #body# #extended# </div> |
Basically, it polls the content area for changes, and when triggered, runs it though a filter. The above is extensible, and by adding additional “apply_shortcode
” calls from “apply_filters
“, more shortcodes can be simulated.