Thord Daniel Hedengren - Smashing WordPress_ Beyond the Blog-Wiley (2014)

(avery) #1

CHAPTER 6 • Advanced Theme Usage 137


As you can see, adding a class to post_class() is as easy as adding a parameter. A similar
solution is used when you need to retain post-specific styling through post_class(), but it
acts outside the loop. Then, you need to tell post_class() to return the ID, which is done
by altering the code to this:


<?php post_class( '', $post_id ); ?>


As you can see, post_ID() can let you add pinpointed style to one particular post, but
post_class() is more useful because it lets you style sets of posts, and also that one post
should you need to. In fact, you can question if the post_ID() part is still needed, but as
long as it is in the default theme, it obviously is, and it may be useful in the future.


BODY CLASS STYLING


Another way to apply some styling to various parts of a WordPress site is the body_class()
template tag, introduced in version 2.8. Basically, it is for the body tag what post_class()
is for the blog post container. This is how you use it:


<body <?php body_class(); ?>>


Depending on where you are on the site, the body tag will get different classes. Say you’re
reading a post with the ID 245 and you’re logged in. That would return this body tag:



A category listing would return other classes, and a tag listing another set again. Pages, the
front page, search — every imaginable part of your site will return more or less different
classes for your body tag.


Why is this good for you? Say you want a different size for your h2 headings, depending on
whether they are loaded in a listing or in a single post. You can define this by adding classes to
the various template files, or you can do it in CSS with the classes outputted by
body_class().


First, you need to find out what classes are returned and when. See the class listing later in this
section to get a bearing of what you have to play with, but for now, it is enough to know that
the class single is passed to the body tag when viewing a single post and archive is
passed for most listings pages (much like the template tag archive.php, which is called for
both category and tag listings should category.php and tag.php not be present in the theme).
That means you’ll work with these classes. Here is the code you may want to put in your style
sheet:


body.single h2 { font-size: 48px; }


body.archive h2 { font-size: 36px; }

Free download pdf