WordPress Developer should learn about apply_filters() and why?

The first thing that came into my mind when hearing add_filter() and apply_filters() was yeah! no more editing the template to make a small changes. Well that’s the dream of any WordPress developer when working on a WordPress Theme Framework such as Genesis or Thesis which have constant update whenever a new version of WordPress released.

What are add_filter() and apply_filters()?

Nonetheless to say, how much do you know about add_filter() and apply_filters(). To put it simple, it is a functions that let you make changes to a themes or templates without editing the file. However the template itself need to have apply_filters() wrapped in editable area before you can use add_filter() to make the edits via functions. Here are few example you can apply to your next theme code for better accessibility and improve the edit process in child theme.

Filterable for any text

Sometime in your theme, you have a string of text like ‘advertisement’, ‘people may like also’ or ‘related post’ that you want user to be able to change without edit the template. Simply wrapped the text like this
[php]echo apply_filters(‘prefix_advertisement_text’, ‘advertisement’);[/php]
Users just need to add this to child theme function to change it
[php]function prefix_myad_text() {
return ‘MY CUSTOM TEXT’;
Now the ‘advertisement’ text will change to ‘MY CUSTOM TEXT’.

Filterable for change content to excerpt

[php]echo apply_filters(‘prefix_the_content’,get_the_content());[/php]
if the user want to change the full post content to excerpt post only, he can add this to his child theme functions.php
[php]function prefix_edit_content() {
return get_the_excerpt();
now any code that wrapped with apply_filters(‘prefix_the_content’,FUNCTIONS) will change to excerpt text rather than full content.

code that use echo the_content(); will not be affected.

Filterable for featured image thumbnails

instead of using the default the_post_thumbnail(‘thumbnail’), you could try use this
[php]$thumb = get_post_thumbnail_id( $post->ID ), ‘thumbnail’);
$thumb = apply_filters(‘prefix_my_thumb’,$thumb);
echo $thumb;[/php]
so when user want to change ‘thumbnail’ to ‘medium’ in child theme, they can add this code to child theme functions
[php]function prefix_edit_thumbnail() {
global $post;
return get_post_thumbnail_id( $post->ID ), ‘medium’);
Now all the effected the_post_thumbnail() will change from using ‘thumbnail’ to ‘medium’ for their featured images.

Final Conclusion

These are just a basic explanation of how add_filter() and apply_filters() work. There are more advanced filtering that can be learned so your future theme users can enjoy the less troublesome theme edits via child theme whenever you made updates to your themes.

Scroll to Top