Getting Post Information Outside the Wordpress Loop


Question

I know there are functions to like is_single() that will return data about the page, but I'm looking for a way to get the following information outside of the loop:

The category of the single post.

AND

The title of the single post.

All I would really need is the post ID in question and I could get all the other information. I've looked through the functions reference in the codex, but I haven't found anything. Is this impossible because the script doesn't even get that information 'til the Loop runs?

(I would need this information in both the header and footer, so before and after the PHP script for the loop, if that is a problem.)

Hopefully someone can offer some insight.

EDIT: To clarify: I want the information to be from the post that is loaded in the loop on the "single" page. (AKA the post they are viewing.) So how would I get this ID in the first place? Basically, when viewing a post, I want to get its category or title, but not while the loop is going.

1
4
9/8/2009 11:29:19 AM

Accepted Answer

You could execute your own query and return a $post object and then access it's attributes through something like

echo $post->title;

Read about $wpdb and Custom Queries on the Codex. Basically you could run a SQL query using the ID as a where filter through its $wpdb object.

Another option, more WP-like, would be to use a Custom Query Post, where you could define another loop, returning only your post using its id:

query_posts('p=2010'); // 2010 being the post's ID  

Then you could run the alternative loop and use the similar $post object to display some information.

3
9/8/2009 12:19:16 AM

This is actually quite simple.

// Gets an array of post objects.  
// If this is the single post page (single.php template), this should be an
// array of length 1.
$posts = get_posts();
// The post object contains most/all of the data that is accessible through the 
// normal functions like `the_ID()`, `the_author()`, etc
var_dump($posts[0]->ID);

This can be performed outside of and it doesn't affect the normal loop. For example, my single.php template looks like this (line numbers included):

1. <?php
2. get_header(); 
3. $posts = get_posts();
4. var_dump($posts[0]->ID);
5. ?>
6. <div id="post">

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon