Thursday, July 17, 2014

Style Posts Individually

The problem.
Your blog has a lot of posts, but the posts aren’t all of the same type. To give special styling to one or more of your posts, you can take advantage of both the post_class() function and the post ID.

The solution.

To apply this trick, just open your single.php file, find the loop and replace it with the following:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<h3><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h3>
<?php the_content(); ?>
</div>
<?php endwhile; else: ?>
<?php _e('Sorry, no posts matched your criteria.'); ?>
<?php endif; ?>
 
 
Code explanation.

The important part is mostly in line 3. Here, we have added the PHP post_class() function. Introduced in WordPress 2.8, this function adds CSS classes to the post. For example, it can add:
  • .hentry
  • .sticky
  • .category-tutorials
  • .tag-wordpress
With these CSS classes now added, you can now give a custom style to all posts that have the sticky tag or those that belong to the tutorials category.
The other important piece of this code is id="post-<?php the_ID(); ?>". By displaying the ID of the post here, we’re able to style a particular post. As an example:
#post-876{
  background:#ccc;
}

No comments:

Post a Comment

Dharamart.blogspot.in