Return The Post ID and Modify A Specific Entry Inside a WordPress Loop

I recently needed to slightly modify the output for a specific entry inside a category loop on a client’s WordPress install. Having a terrible memory, I seem to always forget functions for basic things like this, and this case was no exception.

A few keystrokes in Google, and I was quickly reminded that WordPress does in fact have a built in function that returns the ID inside the loop –> get_the_ID

And using it is simple as…

<?php

$id = get_the_ID();
if($id == 2817): ?>

 /* Do Something Special Here */

<?php endif; ?>;

*There is also the_ID() which *displays* the ID inside the loop, but that’s not what I was after, since I needed to run a conditional check for a specific post

I also was reminded that if I didn’t want to use the WordPress built-in function, I could just grab the ID from the global $post object. So this conditional works as well…

<?php if($post->ID == 2817): ?>

*Depending on how/where you do it, you may have to declare the $post variable as global before this works. Example:

<?php

global $post;
if($post->ID == 2817): ?>

 /* Do Something Special Here */

<?php endif; ?>

You may be wondering why you would ever need to modify the output for a specific post that’s moving through the loop and I agree, this is not something you’ll probably have to do very often.

But imagine a situation where you are using the WordPress post/category paradigm in an abnormal fashion…for example, a list of people/profiles sorted by name and not date. (I’ve done this many times on client sites).

Perhaps there is one person..maybe the CEO who needs a little extra spizazz on his entry in the category loop (perhaps different/more custom fields, additional images etc etc).

Using this conditional allows me to modify the template for his specific entry very quickly without too much fuss.

Also, I should point out, if what you want to do is purely visual (as opposed to modifying the actual HTML output as I needed to do) you’re much better of using some plain ol’ CSS.

By default every entry in the loop should have a custom #id attached to it in the html. So, for a specific entry, if you just need to just change colors, change size, add borders, emphasize text etc etc….probably best to do that in your CSS file without even touching PHP to add extra markup.

#post-2817 { border: 2px solid black; }
This entry was posted in Tips & Tricks. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>