How to check to see if there are pages or posts before displaying in WordPress
When I’m programming a new theme in WordPress I’ll often want to check to see if there are going to be any results before I write content to the page, but often the process of calling the results will display it.
For example, if I want to list a series of pages inside a <ul> tag I first want to know if there is going to be a list of pages to write otherwise I will be writing an opening and closing <ul></ul> with nothing in the middle or worse, a title as well. To avoid this, here’s what I do:
[source lang="php"]<?
$list = wp_list_pages(‘echo=0′);
if ($list) {
echo "<h2>My pages</h2>";
echo "<ul>";
echo $list
echo "</ul>";
}
?>[/source]
The code example above simply uses the echo=0 option to preload the page list results into a variable called $list, next I simple check if $list has a value and if it does, I write the header and <ul> tags as well as the variable $list. If there are no pages, nothing is written.
I’ve build a similar function into three recent plugins, where you can preload the results into a variable using a show attribute by setting the value to false:
- $list = scheduledPosts(’show=false’);
- $list = randomPosts(’show=false’);
- $list = popularPosts(’show=false’);






nice stuff chris, thx for the posting this artical..