In typography sensitive projects we might want to allow our WordPress media captions to have headings (or some sort of accentuated text) before the normal caption text. Let’s just call them WordPress caption headings.
The simplest approach is to manually add the appropriate HTML to the caption text. However, this will quickly become an annoying task, if we have to write a lot of image captions.
Simple JavaScript Solution for WordPress Caption Headings
I find it most convenient to write the heading text directly inside the caption field and define a special character (or a sequence of characters) that separates the heading part from the normal text.
The following JavaScript snippet uses two pipe symbols („||“) as the separator, so a caption would look like this: „This is the heading part || This is the content part of the caption text.“
Everything before the separator will be wrapped in span tags with a custom class of ‚bub-caption-heading‘. We can then use this class to add specific styles for the heading part of the caption.
/**
* Captions Headings Function
*
* Identifies and wraps the heading part of caption texts using
* a custom separator.
*
* Instructions: In your caption text use two pipe symbols ("||")
* and a single space before and after to separate the heading
* part from the rest.
*/
(function() {
// Select captions.
var caption = document.querySelectorAll( '.wp-caption-text, .featimg__caption, .caption' );
// Choose a separator (one or more characters) for the heading part.
// Text before the separator will be treated as the heading.
var separator = '||';
// Choose a heading tag and class.
var beforeTag = '';
var afterTag = '';
for ( i = 0; i < caption.length; i++ ) {
var captionString = caption[i].textContent;
var separatorIndex = captionString.indexOf( separator );
// Skip captions that don't contain the separator.
if ( separatorIndex <= 0 ) continue;
// Capture the heading part.
var headingString = captionString.slice( 0, separatorIndex ).trim();
// Wrap the heading part and remove the separator.
caption[i].innerHTML = captionString
.replace( headingString, beforeTag + headingString + afterTag )
.replace( separator, '' );
}
})();