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.
This is actually quite simple.
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):You could execute your own query and return a $post object and then access it’s attributes through something like
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:
Then you could run the alternative loop and use the similar $post object to display some information.
This is what I use inside the loop to run an new query; I just tried it outside the loop and it works, on a
single.php
template page. This will give the title of the latest post inmycategory
. I don’t know how to pull the category ID, though.After the query has run, try running:
The information you are looking for is probably in
$wp_query->query_vars
or$wp_query->post
You can use the $wp_query global object, and address all returned posts like this
Then, if for instance you need to know if the first post is of a certain post_type, you can do this:
Couldn’t you store the $post information in a separate variable on the page, then just echo the data you need out later when you need it (ie, outside the loop)?
This is predicated on needing the data after the initial loop has run.
The usual thing is to create “second loop” which would extract needed post, hence your needed data.