The mother of all WordPress body tags
It took us a long time to perfect this gorgeous body tag, it includes everything you’d want as a front end developer, it inserts the name of the page you’re on into the class attribute, it adds the pages parent as the id, works on home, 404, search, tag, and category pages as well.
NOTE: we’ve updated the code to also show what template you’re using, so if you have an old version, grab it again below
NOTE: In order for this to work you’ll need to set your permalink structure to something that uses post names in the urls instead of numbers. You set that in Settings > Permalinks. We suggest /%postname%/
So without further ado, here’s it is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<body id=" <?php $post_parent = get_post($post->post_parent); $parentSlug = $post_parent->post_name; if (is_category()) { echo "CategoryPage"; } elseif (is_search()) { echo "SearchResults"; } elseif (is_tag()) { echo "Tag"; } else { echo $parentSlug; } ?>" class=" <?php global $wp_query; $template_name = get_post_meta( $wp_query->post->ID, '_wp_page_template', true ); $tn = str_replace(".php", "", $template_name); echo "template-".$tn." "; ?> <?php if (is_category()) { echo 'category'; } elseif (is_search()) { echo 'search'; } elseif (is_tag()) { echo "tag"; } elseif (is_home()) { echo "home"; } elseif (is_404()) { echo "page404"; } else { echo $post->post_name; } ?>" > |
Also here’s a more compact version (less readable but still works the same) if you want to save space in your template and don’t think you’ll be editing the code. You should probably just use this one:
1 2 3 4 5 6 |
<body id="<?php $post_parent = get_post($post->post_parent); $parentSlug = $post_parent->post_name; if (is_category()) { echo "category-template"; } elseif (is_archive()) { echo "archive-template"; } elseif (is_search()) { echo "search-results"; } elseif (is_tag()) { echo "tag-template"; } else { echo $parentSlug; } ?>" class="<?php global $wp_query; $template_name = get_post_meta( $wp_query->post->ID, '_wp_page_template', true ); $tn = str_replace(".php", "", $template_name); echo "template-".$tn." "; if (is_category()) { echo 'category'; } elseif (is_search()) { echo 'search'; } elseif (is_tag()) { echo "tag"; } elseif (is_home()) { echo "home"; } elseif (is_404()) { echo "page404"; } else { echo $post->post_name; } ?>"> |