Jun
13
2009

Remove wp_list_pages() Links for Parent Pages

by   |  Posted in Tutorials  |  40 comments

Creating a page list in WordPress is super easy. All it takes is one function call: <?php wp_list_pages(); ?>. The only problem with the list is if you have sub-pages categorized under pages that you only want to use as a way to organize your pages. Your parents pages are still linked to in the list but most likely they will be empty. I decided to create a quick function to solve this problem.

Just place this in your theme’s functions.php file.

<?php
function removeParentLinks() {
$pages = wp_list_pages('echo=0&amp;title_li=');
$pages = explode("</li>", $pages);
$count = 0;
foreach($pages as $page) {
if(strstr($page,"<ul>")) {
$page = explode('<ul>', $page);
$page[0] = str_replace('</a>','',$page[0]);
$page[0] = preg_replace('/\<a(.*)\>/','',$page[0]);
if(count($page) == 3) {
$page[1] = str_replace('</a>','',$page[1]);
$page[1] = preg_replace('/\<a(.*)\>/','',$page[1]);                
}
$page = implode('<ul>', $page);
}
$pages[$count] = $page;
$count++;
}
$pages = implode('</li>',$pages);
echo $pages;
}
?>

Now just replace your wp_list_pages(); function with removeParentLinks(); and away you go.

NOTE: This only works for page lists that are three levels deep or less.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
Share the love...

Tags: , , , , , , , , , , , , , , , ,

Short URL: http://bit.ly/9JOFKE

Discussion 40 Comments

  1. Pablo on July 18, 2010 at 4:27 pm

    How can I remove the wp_list_pages () links for the selected parent page?

  2. Matt on September 19, 2010 at 11:43 pm

    Does anyone know why this function would break after updating wordpress to 3.0? It worked great for me in 2.7, but once I upgraded it, the parent pages got there links back…

    Any suggestions?

  3. Alex on March 13, 2011 at 7:31 pm

    thanks a lot! it works perfect