Removing wp_list_pages' class from list items via WordPress Filters

23.08.2010
Written by Maleika Esther Attawel
Published in
Development
Tweet Me

I'm certainly not a PHP programmer. Heck, I'm not a programmer at all, unless you count HTML, CSS, and a little Javascript as programming languages, which they are factually not. I am currently coding a design into HTML5 and CSS3 and am integrating it into WordPress. As I'm being quite persnickety regarding the structure and HTML/CSS of a design, I'm quite unnerved by the rather generous addition of classes, ids and HTML elements/attributes that have been coded knee-deep into WordPress'core. Why, oh why can't WordPress let me, a humble but markup-aware user, decide how I create my markup? And why is it required for designers/front-end web developers to dig deep into PHP functions just to be able to get rid of all that extra dispensable markup? No, fun it is not.

But all that whining and complaining aside, WordPress is a good tool. Why be humble...WordPress is an excellent tool! That's why I'm creating another theme that'll soon be distributed all over the net.

It's a theme in which I make use of the wp_list_pages function. If you've used WordPress for a while, you'll know that this function outputs quite a few extra classes by the name of page-item. Well, I don't need them and don't want them in the code. To remove them, I've taken all my PHP know-how, ahem, cough... and timbered together a small function, more precisely, a WordPress filter which has the sole purpose of stripping the class attribute and its associated content. The ingredients with which the page-item class and the HTML class attribute get removed from the markup is as follows:

  1. function remove_page_class($wp_list_pages) {
  2. $pattern = '/\<li class="page_item[^>]*>/';
  3. $replace_with = '<li>'
  4. return preg_replace($pattern, $replace_with, $wp_list_pages);
  5. }
  6. add_filter('wp_list_pages', 'remove_page_class');
This little snippet of code reads (line by line):
  1. 1. Create function remove_page_class
  2. 2. Define a variable $pattern and assign it a regex pattern that selects the li attribute class and its values
  3. Define a variable with the code that you want to replace the above with
  4. 3. I use preg_replace, a function that searches and replaces a regular expression. In this case, I'd like to modify the output of $wp_list_pages, thus my preg_replace searches in $wp_list_pages for the markup that matches the value I specified in my $pattern variable and replaces it with the value of my $replace_with variable

And that's pretty much it. If a PHP guru or— PHP Ninja, as an expert is referred to these days— and find there's a better, leaner method, do shout away. I've just started learning PHP and am grateful for all sorts of input.

Ontwitter

searchme

bookreview