So, in my WordPress adventures, there are times I’ll stray from WordPress’ library of functions for special cases. One of which being when I need to get the ID
of the page/post for a random reson, outside the scope of The Loop.
The Problem
Let’s say in header.php
of my template, I’m pulling a post:
if ( have_posts() ) : the_post(); $current_page_id = get_the_ID(); endif;
This works, but, it increments the cursor of the global $posts
array by one. The issue it caused in one of my older projects was that the blog home page (where the array contains 5-10 posts) was never displaying the most recent post.
The Fix – rewind_posts()
Luckily, WordPress has a nifty little function call rewind_posts()
that will… rewind posts.
if ( have_posts() ) : the_post(); $current_page_id = get_the_ID(); rewind_posts(); endif;
Using this will throw The Loop back to where it should be.
A better way?
An alternative method of grabbing the ID, san-WordPress functions/tags, would be to grab the ID from the global $posts
array. This would save the trouble, but strays from using WP’s built-in library of functions:
global $posts; $current_page_id = $posts[0]->ID;
This works well, and requires fewer lines of code, but I tend to try to stick with the WP functions, as they will aid in keeping your code/plugins/themes future compatible.
No comments yet.
RSS feed for comments on this post. TrackBack URL