The power of filters in WordPress

Filters in WordPress are used to add or override the core functions return. Usually filters come at the end on a script just before it returns the result. A filter send a variable to a range of registered functions that will modify it and return the new variable.

The good thing is that you can have more than one function per filter but also that you can add you own function to existing filters very easily.

Let’s have a look at a quick example. I’ve got a paragraph of text containing road codes (in the uk standard: one capital letter+number). Unfortunately they have been written in lower case. I’ve got 600 posts with those and I can’t edit them one by one. WordPress provides a filter for the main content of each post called the_content.

What I am gonna do is a function that hook to the_content filter and sort out the road codes.

//Capitalise first letter of road code

//hook our function to the_content filter
add_filter('the_content', 'capitalise_road');

//the function called when the_content filter is triggered
function capitalise_road($content){

	//match A456 or M56, etc...
	$pattern = "/([a-z]{1})([0-9]+)/e";
	
	//capitalize the first part of the matched string
	$replace = "strtoupper('$1').'$2'";
	
	//apply the capitalize function to the matched strings
	$content = preg_replace($pattern, $replace , $content);

	//return the modified content
	return $content;
}

Theme frameworks like Thematic provide you with even more filters to hook custom function to and modify almost every function used.

For a comprehensive list of the filters available by default have a look here. As you can see there are quite a few! Now it is up to your imagination to create useful filters.

One response to “The power of filters in WordPress”

  1. Alberto Villalobos Solano

    Thanks very useful, i am going to look deeper on this topic

Leave a Reply

Theme Forest ad
Wordpress Themes Collection ad
Woothemes

Poll

How do you start your WordPress plugins development projects?

View Results

Loading ... Loading ...