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

(avery) #1

50 PART I • Getting Started with WordPress


If the post is marked as sticky, post_class() will add a CSS .sticky class. That way, you
can alter it any way you want. Maybe you want it to have a light gray background, larger type,
or something else? Just add the necessary styles to your style sheet, applying them to the
.sticky class as in the following example:

.sticky {
padding: 15px;
background: #eee;
border: 1px solid #bbb;
color: #444;
font-size: 18px;
}

This CSS code would put the sticky post in a light gray box with a slightly darker frame and
18-pixel-sized default font size. Here it is in action, within a basic loop:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2>
<a href="<?php the_permalink(); ?>"
title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>
</h2>
<?php the_content(); ?>
</div>
<?php endwhile; else: ?>
<p>Some error message or similar.</p>
<?php endif; ?>

In plain HTML, you’d get the following containing div. Notice the classes applied by post_
class() in particular:

<div id="post-1" class="post-1 post type-post status-publish format-standard
sticky hentry category-uncategorized">
<!--POST CONTENT GOES HERE -->
</div>

Want to do more with sticky posts? The conditional tag is_sticky() will help you do some
funky stuff. Maybe you really want to rub in the importance of this post above all others?
Then why not say so:

<?php if ( is_sticky() ) echo 'Super important post! Read it! Now!'; ?>

A bit over the top, of course, but there may indeed be times when it is a good idea to output or
change things if there is a sticky post involved. Say you sell e-books on your blog; you could
use sticky posts to promote your latest one:

<?php if ( is_sticky() ) echo 'The latest e-book release by yours truly'; ?>
Free download pdf