Dynamic Headings in WordPress « Dented Reality.php

Send Snippet To: Save this snippet to Code Collector Pro -- view all ian.k's snippets
language: PHP
license: Other

Code for Snippet:

One thing that’s always bugged me in writing Posts/Pages content within WordPress is that you have to cater for different presentation possibilities. If you’re into web-standards, then that makes life difficult for things like headings (h1, h2, etc), when a block of content is presented in different contexts.
Ideally, your page should be structured with an h1 tag around the title of the most important concept on the page, an h2 around a sub-topic/concept, etc. On your home page, the h1 usually ends up going around your logo/site title, since that’s the over-arching concept. Then under that, you might have a listing of recent posts. Each of those posts should probably have their titles in an h2. No problem so far, right? You just set up your template like that and you’re good to go.
In the content of each post however, this means that you’re down to an h3 if you have sub-sections within the post. No problem, just use that markup and everything’s golden. Until you view a single-post/page and then your structure doesn’t really make sense any more. Ideally, on these pages, the title of the post would be an h1 and those h3s would now be h2s. What to do?
Easy, drop the following code into your functions.php file (within your theme, or I guess you could turn it into a plugin if you were into that) and it will dynamically adjust your headings for your homepage (and archives, tag pages, etc).
So when you’re writing a post, write to target a single-page view, where the title of the post/page itself is h1, and your structure within the post should start from there. The code above will take care of fixing it up for the homepage, archives etc (bumping all heading tags “down” one level).
function beaus_dynamic_headings( $content ) {
 if ( is_singular() )
 return $content;
 $content = str_replace( array( '<h5', '</h5>' ), array( '<h6', '</h6>' ), $content );
 $content = str_replace( array( '<h4', '</h4>' ), array( '<h5', '</h5>' ), $content );
 $content = str_replace( array( '<h3', '</h3>' ), array( '<h4', '</h4>' ), $content );
 $content = str_replace( array( '<h2', '</h2>' ), array( '<h3', '</h3>' ), $content );
 return $content;
add_filter( 'the_content', 'beaus_dynamic_headings' );
comments powered by Disqus


Link to this snippet:

Download to Code Collector

To use the direct link to your snippet on CodeCollector.net either copy the html from the above section or drag the Download to Code Collector to where you would like to use it.

More Info:

Times Viewed: 401
Date Added: 2013-03-18 05:18:49
Last Modified: 2014-04-07 14:16:07

Web Analytics