wp_list_pages() is one of the most common WordPress template tags. Sometimes, the little white space that some browsers add to the output of this function can create a big mess in your theme’s template, making it hard to style, especially when trying to create a horizontal list. The fix for this is quite simple and requires minimum coding knowledge, if none at all.

The Problem

The wp_list_pages() generates either a series of <li> elements containing links to all of you blog’s pages, or a full unordered list with a heading at the beginning.
The output of this list looks like this:

<ul>
<li><a href="#">Page name</a></li>
<li><a href="#">Page name</a></li>
</ul>

While some browsers don’t have a problem with elements being generated on new lines, in some, this method causes a white space to show up in front of each list item. This space becomes visible and annoying when trying to create a horizontal menu with background colors and equal horizontal spacing.

The Fix

To get rid of the white space, your output would need to look like this:

<ul><li><a href="#">Page name</a></li><li><a href="#">Page name</a></li></ul>

This can be achieved by using a small PHP function that will take the code generated by wp_list_pages() and turn it into something similar to the example above. To make this function available for use in your templates you need to edit the “functions.php” file, found in you theme’s directory. If you don’t have such a file, create an empty one and name it “functions.php”.

In functions.php add the following code at the beginning or at the end of the file. Just be careful not to paste it inside another function and cause the script to break.

function qbkl_nospace($input) {
$output = str_replace(array("n", "r", "t"), "", $input);
echo $output;
}

White space fix

Usage

To apply the fix, simply find the wp_list_pages() in your theme’s template (usually header.php or sidebar.php) and edit the code according to the following example:

Find:

<?php wp_list_pages(); ?>

Replace with:

<?php qbkl_nospace(wp_list_pages()); ?>

This fix works with any function or template tag that generates the same problem.

The white space generated by wp_list_pages() has been a nightmare for many WordPress themes designers. It doesn’t have to be one for you!

Where is wp_list_pages() located?

Although it’s not recommended that you alter the base code of WordPress, advanced users might feel like taking such a job.

If you need to alter the output, wp_list_pages is defined in the post-template.php file, in the “wp-includes” folder of your WordPress blog.

For further tweaking, you might also need to adjust the walk_page_tree function, located in the same file, which makes use of the class Walker_Page, extending the Walker class, both located in wp-includes/classes.php.

* The above file names and locations are confirmed for WordPress 2.5 to 2.6.3.

If you’re having any questions or need further assistance, please use this post’s comment form.