Skip to content

Dynamically Add Markup to WordPress Posts

I recently needed to add Facebook and Instagram icons in front of links within a random WordPress page, and—rather than actually adding the required markup to the page content—wanted to do so dynamically. (Actual in-post markup is so easily messed up by clients!)

jQuery

I settled on jQuery, using the JavaScript framework’s powerful selectors to single out the exact links and insert Genericons icons in front of them, much like this:

jQuery( function( $ ) {
  $( '<span class="genericon genericon-facebook"></span>' ).insertBefore( '.entry-content a[href*="facebook.com"]' );
  $( '<span class="genericon genericon-instagram"></span>' ).insertBefore( '.entry-content a[href*="instagram.com"]' );
} );

Since the Genericons icon font was already being loaded, it only took very little additional styling to get things to look great.

Pure PHP

Parsing the post content in PHP would’ve been possible, too. (I did something very similar in my super-simple Code Prettifier plugin—and then went for the much simpler jQuery variant with JS Code Prettifier.) Better contain that DOMDocument magic inside a rather specific if statement, though, to prevent it running multiple times per page.

Custom Fields

Yet another possibility, if the links in question make up a menu of their own: have the links inputted using custom fields, then—using a filter hook or custom theme template—generate the menu on the fly, and add whatever code needed.

Note: This may actually be a case where Gutenberg would’ve come in handy instead. Using WordPress’s new content editor, I could’ve added a list or custom HTML block and manually put in the additional code. The risk of the client messing up would be small: there’d be little need to ever touch that block.