Tuesday, April 17th, 2012

Using correct post heading tags on WordPress index/blog template

Generally in the WordPress loop we’ll create one snippet of code which is repeated on a blogs landing page showing your first 5 – 10 post snippets. The loop will output something like the below:

<article>
    <h2>Post Title</h2>
    <p>Post Excerpt…</p>
    <p><a href="">Read Full Article</a></p>
</article>

<article>
    <h2>Post Title</h2>
    <p>Post Excerpt…</p>
    <p><a href="">Read Full Article</a></p>
</article>

<article>
    <h2>Post Title</h2>
    <p>Post Excerpt…</p>
    <p><a href="">Read Full Article</a></p>
</article>

I’ve done this myself many times, but in an ideally world the heading tags would run in sequence: h1, h2, h3, h4, h5 and h6. Generally I’ve not worried too much about this – especially now as with HTML5 we can use more than one heading tag per page so long as it’s wrapped in it’s own article tag – though I have no idea how google views this.

Updating some code this afternoon I decided to make the article tags run in turn of authority and its actually ridiculously easy.

<?php if (have_posts()) :
 $postCount = 0; ?>
 <?php while (have_posts()) : the_post();
 $postCount++; ?>

                <?php if ( $postCount <= 6 ) { 
                    echo ('<h'.$postCount.'>');
                } else {
                    echo ('<p class="article-heading">');
                } ?>

<?php the_title(); ?>

                <?php if ( $postCount <= 6 ) { 
                    echo ('</h'.$postCount.'>');
                } else {
                    echo ('</p>');
                } ?>
<?php the_content('Read more'); ?>
<?php endwhile; ?>
<?php else : ?>
 <?php endif; ?>

All the code above does is count the post as they’re pulled from the database and use the appropriate heading tag ending up with a paragraph tag if we’re showing more than 6.

Job done. Feel free to copy paste and use on your own sites.

 

Leave a Reply