Styling WordPress Pages as Inline List without CSS
/* Posted May 3rd, 2011 at 2:41pm [Comments: none] *//* Filed under General */
WordPress has a number of great built-in functions that you can use throughout your theme, but you’re pretty much limited to accepting any list of pages output as ul lists. But what if you don’t want a vertical top to bottom unordered list? Would it be possible using CSS to style the list so that the entire list appears on one line and reads left to right? Yes, you can definitely add the CSS inline property to the list to make this happen. While this works, there is one small problem. I wanted to make my list of pages look like a navigation block with a simple vertical bar character separator. Really simple, like this:
About Me | Contact Me | You Get | The Point
This type of navigation-looking output of all your WordPress pages does not use a list at all, so using the built-in function wp_list_pages is out of the question. There is no way to get an output without each page being wrapped in li tags. So instead, I found a great alternative function that works very much like this one but allows me to control the output called get_pages.
In your WordPress theme where you want to output all your pages horizontally in one line, use this simple function that I came up with to style it exactly as I wanted it to look in the example above.
?php
$pages = get_pages('exclude='); // you can add page IDs to exclude if you want
for ($i = 0; $i count($pages); ++$i)
{
if ($i != 0)
echo ' | ';
echo 'a href="'.get_page_link($pages[$i]-ID).'"'.$pages[$i]-post_title.'/a';
}
?
That’s it! You can easily tweak the separator character (in this case I used the vertical bar but you can use bullets, », etc). No messy SQL to write (which I was just about to do before I stumbled on this function in the WordPress Codex) and the code is very easy to understand. Look at the documentation if you want to do fancier things like sorting the page results. By default it is simply sorted alphabetically which was OK for my needs. Using this, you can even add a “Home” link to the beginning of the list like many navbars do, something not possible with the built-in WordPress page listing function. This also beats hard-coding the page URLs since it reduces the theme’s portability when applied to other websites. If you’ve got a few websites using the same theme, then you’ll appreciate why this sort of broad compatibility is quite critical.
If you have knowledge of an even better way to do this, you are welcome to share it in the comments for everyone’s benefit.
Tags:






