Cleaning up wp_list_pages()

Follow @tristarweb

Today I am going to show you how to clean up the wordpress wp_list_pages() function. Lets say I wrote the following code in my web design page:

        <?php wp_list_pages('title_li=); ?>

This will print something like:

         <li class="page_item page-item-1"><a href="" title="Home">Home</a></li>
         <li class="page_item page-item-2"><a href="" title="About">About</a></li>
         … and so on..

As you can see the href attribute contains the full url. This is not seo friendly and would be better if it were /pagename. The solution to this is to use the php string replace function. Copy and paste the following php code replacing the example domain with your full domain name.

        $clean_page_list = wp_list_pages('echo=0&title_li=');
        $clean_page_list = str_replace('','',$clean_page_list);
        echo $clean_page_list;

As you can see from the code above, I passed in the argument ‘echo=0′. This is important in order to assign the wp_list_pages() function to a variable. This is because wp_list_pages() echoes the result by default, therefore, putting ‘echo=0′ means it will return the result as a string, rather than echoing it.

Now navigate to your page and view the source code. You should notice that the html looks something like the below:

         <li class="page_item page-item-1"><a href="/" title="Home">Home</a></li>
         <li class="page_item page-item-2"><a href="/about" title="About">About</a></li>
         … and so on..

This is a lot tidier and more SEO friendly. You could go one step further and replace the li classes but I will leave that to you guys.

About robert

Hi my name is Rob Hills. At most times you will find me playing around with Magento and Wordpress. I am always looking to improve my web development knowledge – this ranges from PHP, Javascript, jQuery, XML etc. Other than web development – I produce Dance Music. My biggest achievement is getting my track played by Kutski on Radio 1..

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Please wrap all source code with [code][/code] tags.

Follow Tristar on Twitter