Tuesday, April 7, 2015

Difference between add_filter and apply_filters

In wordpress, apply_filters and add_filter are two different hooks.

apply_filters
The callback functions attached to filter hook $tag are invoked by calling this function. This function can be used to create a new filter hook by simply calling this function with the name of the new hook specified using the $tag parameter.


You use apply_filters to filter a given $value - with respect to the value itself as well as optionally provided variables $var_1 through $var_n.

add_filter
Hook a function to a specific filter action.
add_filter( $tag, $function_to_add, $priority, $accepted_args );

You use add_filter to hook a custom function to the given filter action ($tag), which you might have generated by apply_filters before.

In the most basic terms, apply_filters is used to initialise a filter hook. add_filter assigns a new function to hooks that have already been created.

Example:

To filter the widget title.
apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Pages' ) : $instance['title'], $instance, $this->id_base ); // Refer : https://codex.wordpress.org/Plugin_API/Filter_Reference/widget_title

function custom_widget_title() {
 $title = 'Welcome';
 return $title;
}
add_filter('widget_title', 'custom_widget_title');

No comments:

Post a Comment