How to Use Filter Hooks

A filter is a function that takes in some kind of input, modifies it and then returns it. It intercepts, manages and returns the data before rendering it to the browser.

According to WordPress, the basic steps to adding your own filters to WordPress are:

    1. Create the PHP function that filters the data.
    2. Hook to the filter in WordPress, by calling add_filter()
    3. Put your PHP function in a plugin file, and activate it. (You can use functions.php file as well.)

Let’s say, for instance, you want to add your own customized page menu instead of the default WordPress page menu.

The hook $args = apply_filters( 'wp_page_menu_args', $args ); occurs in wp-includes/post-template.php, which is a core WordPress file.

Since, you want to manipulate and change the core file, you need to create a function that filters that data.

In this example, we will use a catcheverest function.

function catcheverest_page_menu_args( $args ) {
	$args['show_home'] = true;
	return $args;
}

So, you create a function for your own page menu. And then call add_filter() to hook the filter in the required place.

In our case, it’s:

add_filter( 'wp_page_menu_args', 'catcheverest_page_menu_args' );

We will need to add this after we define the function, and then we’re done.

But, how do we know which functions, WordPress core or parent theme, can be filtered by another function?

The solution is easy. You will need to search for apply_filters(). Any function using apply_filters() will let itself be filtered by another function.

In our example it’s $args = apply_filters( 'wp_page_menu_args', $args ); which is a WordPress core file.

Let’s take another example:

Maybe you don’t want the default […] excerpt to show on your theme. So, you can use the following filter to change it.

/**
 * Replaces "[...]" (appended to automatically generated excerpts) with catcheverest_continue_reading().
 *
 */
function catcheverest_excerpt_more( $more ) {
	return catcheverest_continue_reading();
}
add_filter( 'excerpt_more', 'catcheverest_excerpt_more' );

By using this technique, you can use add_filter to manipulate data and keep your desired function.

Leave a Reply

Your email address will not be published.