3Apr2008

I was recently working on a new WordPress theme when I had need to modify the title of pages before output. The style I was attempting to use involved wrapping <span> tags around the title (inside of the href tags). The wp_list_pages() function returns pages (which are basically the same as posts) and has several arguments that you can pass to customize it’s output. However, modifying the title output is not one of the arguments.

Filters to the rescue! I simply opened up the functions.php file and added a function like this:

function title_span_filter($content)
{
  return '<span>' . $content . '</span>';
}

Pretty simple, eh? All that is left to do is to register this function as an appropriate filter, which you can do like this:

// Add Filters
add_filter('the_title', 'title_span_filter', 1);

The first parameter tell WordPress which function/activity you want to “hook” into. The second parameter is the name of your function. The final parameter is a priority specifier. The lower this priority number the earlier it will execute.

Done! Now instead of output like this:

<li class="page_item"><a href="...">Page Title</a></li>

I get this:

<li class="page_item"><a href="..."><span>Page Title</span></a></li>

For extra credit you actually throw all of this into a plugin. That way you wouldn’t necessarily have to modify any of your theme files.



2 Comments

1

Where does the “add_filter” code snippet go?

Also, how do I apply this filter to only certain items in my navigation hierarchy?

Thanks


2

I generally put the add_filter snippet at the end of the functions.php file in the theme. That is unless you are working with a plugin, then you can just put it at the end of your main plugin file.

I had a hard time with this code because it is global. So I ended up looping through the pages manually. See my follow-up post here: Looping Through Pages In WordPress


2 Trackbacks

  1. sharewp.info
  2. Looping Through Pages In WordPress | franzone.com

 




Leave a comment