Sometimes, you may want to access post data outside of the WordPress loop. Unfortunately, WordPress functions such as the_title()
or the_content()
can't be used outside the loop. In this recipe, I'll show you how to access post data anywhere on your theme, without using the loop.
Before I show you the code, you have to know that each time you'll use the following function, it will execute a SQL query on your WordPress database. This isn't a problem itself, but you shouldn't use the following function usually, in order to avoid extra loading time.
As we have seen, WordPress has a very useful function to get post data outside the loop called
get_post()
. Carry out the following steps to create a PHP variable that will contain all of the available data from the post:$data = get_post(10);
You now have a
$data
object which contains all post data available. To display the data, add the following code:echo $data->post_title...