Pin It
Pages Menu
TwitterRssFacebook
Categories Menu

Posted by on May 20, 2013 in Wordpress Tutorials | 0 comments

Quick Tutorial on WordPress Filters For Plugin Development

Quick Tutorial on WordPress Filters For Plugin Development

Action hooks and filter hooks are very different according to functionality what both provide. Filter hooks allows you to change the output of code in the way you want. So difference between action hooks and filter hooks is that action hooks allows you to add code and filter hooks allows you to overwrite code.

To have a full grip on filter hooks, you must know about a filter hook apply_filters($tag, $value) where $tag represents the name of the filter hook and $value represents the parameter passed to any filters added to the hook. One important point you should keep in mind that $value parameter must be returned back to WordPress when you are writing a filter for WordPress plugin development or any other purpose.

Below is the basic code example of using apply_filters().

[code type=”php”]

<?php

apply_filters( ‘template_include’), $template);

?>

[/code]

What do you think about Filter?

A filter in WordPress is a type of a function registered for a filter hook. The main function would take one parameter at-least and return that parameter after executing whatever code. In practice, filter hooks are not able to do anything. But they exists so that it can be changeable by plugin developers.

When you are calling a filter hook via apply_filters(), then any filter which are registered for the hook are executed. So before calling apply_filters(), you must add a filter via add_filter() function. Syntax for add_filter() is:

[code type=”php”]

<?php

add_filter($name_filter, $function, $priority, $accepted_args);

?>

[/code]

We have already discussed about $tag parameter above. $function represents the name of the function that you want to executed to manipulate the output. $priority takes the integer, if no value is given then it will set to 10 by default. $accepted_tags represents the number of parameters your filter function can accept.

If you are a WordPress developer, you must know a function wp_title which is a filter hook that is responsible for an HTML tag <title> . So now I’m giving you an example of using filter hook.

[code type=”php”]

<?php

add_filter( ‘wp_title’, ‘adding_site_title_now’, 10, 2);

function adding_site_title_now ($tit, $separator) {

// First Get the Site Title

$get_tit = get_bloginfo(‘name’);

//Now append the $get_tit value to the $tit variable

$tit .= $sep . ‘ ‘. $get_tit;

//Now return back the title

return $tit;

}

?>

[/code]

Post a Reply

Your email address will not be published. Required fields are marked *