WordPress Action and Filter Hooks Tutorial (+10 Examples)

In this WordPress tutorial for beginner developers, I will explain WordPress Actions and WordPress Filters and how you can use these WordPress Hooks in your theme or plugin, easy and understandable. This tutorial also contains +10 helpful examples for those who want to see this WordPress tutorial in action.

3.6666666666667 from 5
from 3 user
(Rate this post)

First, I guess it’s better to explain what is a WordPress Hook (Actions or Filters) and why WordPress Hooks are essential to developers.

WordPress let developers hang their custom functions to its core functions throughout WordPress Hooks. WordPress Hooks are two parts: WordPress Actions and WordPress Filters.

What are WordPress Hooks?

WordPress developers can modify WordPress functionalities and returning content by using Hooks.

Hooks can hang a custom function to a WordPress core function.

The developer can set function execution order (A critical parameter when you want to hook multiple functions).

Hooks are often easy to use. to understand them better, we categorize them into two parts: Actions and Filters.

Use WordPress Actions when you want to run a function at the exact moment when a core function is executing.

Use WordPress Filters when you want to modify WordPress returning content at the exact moment when core content is returning.

Why are WordPress Hooks necessary for developers? (sometimes non-developers too!)

Two years ago, In an article, I told developers:

Actions and Filters are the primary way to connect with WordPress.

If any developer wants to use WordPress at its total capacity, they better learn how to work with WordPress Hooks.

WordPress is a complete system for blogging, but when you want to add custom functionalities, especially when there is no plugin for it, you may need to modify WordPress core functions and control its behaviour.

Developers can use WordPress Hooks to control WordPress behaviour when this system is processing a web page.

What is the difference between WordPress Actions and Filters?

The difference between WordPress Actions and Filters is that the actions are concerned with Events, and filters are concerned with Contents.

When I said Events, I meant occurrences like user log in, saving a post, predefined actions (custom actions defined by you), etc.

When I said Content, I meant the Data printed (or used in another way that is not printable) by WordPress on a webpage (or maybe just on the server). For example, title, short description and the full content of a post.

WordPress Action Hooks

What are Action Hooks in WordPress?

Action Hooks will attach a function to a WordPress core function which is executing when an Event occurs while WordPress is processing a web page.

For example, when you want to execute a function on the server when the user just logged in, you can use wp_login action (keep reading for the code).

How to work with Action Hooks in WordPress?

If you read this tutorial carefully, I said WordPress Hooks attaches a custom function to a core function. So you need a way to tell WordPress that “I have a function” and “I want to run this function after a core function that I know”.

1- Declare the custom function

-> Copy this code to your current WordPress theme function.php file. Or you can create a simple plugin to run codes on WordPress using this tutorial: How to create a Hello World plugin for WordPress in 3 Steps

if(!function_exists('make_user_login_awesome')){
      function make_user_login_awesome(){
            echo "You just logged in, what can we do now?";
            die();
      }
}

2- Tell WordPress which core function you want to run this function after

When you want to tell WordPress that you need to run a function after another, you can use:

add_action("core function", "custom function", priority, number_of_acceptable_arguments)

In the previous step, you just created a NOT attached function.

Let’s attach it to the wp_login, which is a core function that executes when a user just logged in.

This will be the Whole Code after attaching the function:

if(!function_exists('make_user_login_awesome')){
      function make_user_login_awesome(){
            echo "You just logged in, what can we do now?";
            die();
      }
      add_action('wp_login', 'make_user_login_awesome', 20, 0);//this line is just added to attach function
}

The above codes explain

In the first line, you can see we checked if any function named make_user_login_awesome exists or not.

If it does not exist, we declare the function.

In the make_user_login_awesome function, we told the server to die(), because we want to see this text printed after login: “You just logged in, what can we do now?”

Now we attach this function to the wp_login action. using this code:

add_action('wp_login', 'make_user_login_awesome', 20, 0);

You can see add_action function accepts three arguments (actually it’s four).

In this particular order:

  1. Name of the WordPress core action that we want to attach a function to.
  2. Name of our function that we want it to attach.
  3. The priority of execution

we passed wp_login, make_user_login_awesome, and 20 as parameters to add_action function.

When you insert the full code to your function.php or the custom plugin you created for this practice, you can log in to WordPress (admin panel or frontend) then you will see the result.

How to define a custom Action, execute it and attach a custom function to it

WordPress made this functionality available for developers to predefine actions and fire them at the right moment of page processing.

This means that you can create custom Actions for yourself and attach custom functions to them.

Let’s see how you can do that…

Creating a new Action in WordPress is just like attaching a function. We use add_action function.

Use this function to create a new Action Hook in WordPress:

add_action("custom_action_name", "custom_function_name", priority, number_of_acceptable_arguments);

custom_action_name will be the name of your custom Action.

custom_function_name is the name of the function we define (we will, keep reading…)

priority will be the order of execution of our Action (Integer).

number_of_acceptable_arguments is the number of arguments that our custom function accepts (Integer).

Copiable example to try

Just copy this in your function.php or custom module you created:

if(!function_exists('make_user_login_awesome')){
      function custom_function_name($arg1, $arg2){
      	  die("Custom Action is Here! ".$arg1." ".$arg2);
      }
      add_action('custom_action_name', 'custom_function_name', 10, 2);

      do_action('custom_action_name', 'value1', 'value2');
}

If you open WordPress, you will see the message:

Custom Action is Here! value1 value2

This means that our code is working.

You can comment out the last line (do_action(….)) to disable this action.

Attaching a custom function to a custom Action Hook

In the last example, we defined a custom Action Hook and executed it.

Now is the time for a little more complicated example.

Do you remember how to attach a custom function to a core Hook? We will do the same thing for this custom made Action.

Use this code as the example:

function custom_function_name($arg1, $arg2){
	die("Custom Action is Here! ".$arg1." ".$arg2);
}
add_action('custom_action_name', 'custom_function_name',10,2 );

function custom_attached_function($arg1, $arg2){
	echo "I just want to say hi... and... \n";
}
add_action('custom_action_name', 'custom_attached_function', 9, 2);//9 is important number here!

do_action('custom_action_name', 'value1', 'value2');

This will display this text after opening the WordPress:

I just want to say hi… and… Custom Action is Here! value1 value2

You can play with this code. Try changing orders of execution, name of the functions, acceptable arguments, etc.

How to remove an Action Hook

WordPress made this available for developers to remove Action Hooks just like adding them.

Developers can use remove_action function to remove an Action Hook, easy and fast.

This means that you can unhook a function from a Action Hook.

now we can unhook it with this syntax:

remove_action('action_name', 'function_name_to_remove');

In an example, we added a welcome page for users after login, we called the function make_user_login_awesome.

Full code to unhook make_user_login_awesome from wp_login Action Hook:

if(!function_exists('make_user_login_awesome')){
      function make_user_login_awesome(){
            echo "You just logged in, what can we do now?";
            die();
      }
      add_action('wp_login', 'make_user_login_awesome', 20, 0);//this line is just added to attach function

      remove_action('wp_login', 'make_user_login_awesome');//this line is doing the trick!
}

4 examples of WordPress Action Hooks

1- Disable WordPress for gusts and show a custom message (like maintenance messages)

This is an easy one, there is a WordPress Action Hook named init that will be executed when WordPress is loaded (NOT completely) but nothing is printed yet.

In the init stage, the user is authenticated.

Use this example to disable WordPress completely but not for logged in users:

if(!function_exists('my_maintenance_message')){
	function my_maintenance_message(){
		if(!get_current_user_id() && $GLOBALS['pagenow'] !== 'wp-login.php')
			die("This website is under construction!");
	}

	add_action('init','my_maintenance_message',10);
}

After inserting this code, WordPress will show maintenance messages to those who are not logged in.

If you see nothing changed, log out from the admin panel.

We excluded the login page from this message, so you can log in again.

2- Redirect users to a specific post after login

You can redirect users after login into any post you want. you have to know the post id or slug.

We’ll use wp_login action for this matter.

Use this code:

if(!function_exists('redirect_me_after_login')){
	function redirect_me_after_login(){
		$postId = 1;
		wp_redirect(get_permalink($postId));
		exit();
	}

	add_action('wp_login','redirect_me_after_login',10);
}

After running this example, you can see after login, the user will redirect to a post with id 1.

You can change the id by changing the value of the parameter $postId.

3- Display a welcome message, then redirect the user to a specific post after login

For this one, we have to use some JavaScript code.

First, we have to print the welcome message, after x seconds we must redirect the user to a specific post.

JavaScript will handle the redirect part, WordPress will do the rest.

Use this code to show maintenance message then redirect the user to post with id 1.

if(!function_exists('redirect_me_after_login')){
	function redirect_me_after_login(){
		$postId = 1;
		$timerInMilliSeconds = 5000;//5 seconds!
		$html = "<p>Welcome to our website!</p>";
		$html .= "<script>setTimeout(function(){window.location.href='".get_permalink($postId)."'},".$timerInMilliSeconds.")</script>";
		echo $html;
		exit();
	}

	add_action('wp_login','redirect_me_after_login',10);
}

You can set the timer with $timerInMilliSeconds variable.

4- Add an Admin Notice to the WordPress admin panel

Admin notices in WordPress are the messages you can see in your WordPress admin panel.

Some messages are success messages, some are warnings.

Sometimes admin notices are dismissable, sometimes they are not.

In this example, I show you how you can display a WordPress dismissable warning message for admins.

if(!function_exists('my_admin_notice_message')){
	function my_admin_notice_message() {
		?>
		<div class="notice notice-warning is-dismissible">
			<p>This is just an example!</p>
		</div>
		<?php
	}
	add_action( 'admin_notices', 'my_admin_notice_message' );
}

You can control the message’s UI by changing classes in the HTML code.

For example, if you want to display a success message, you can replace notice-warning with notice-success.

is-dismissible class makes this Admin Notice a dismissible message.

You must see the result on all admin pages.

Something like this on top of the page:

Admin Notice Example
Admin Notice Example

WordPress Filter Hooks

What are Filter Hooks in WordPress?

Filter Hooks in WordPress let developers modify the Data processed by this CMS.

Developers can use Filter Hooks to modify WordPress Data at runtime.

They can change the value returned by the core WordPress to generate new value.

Developers must attach a function to a Filter Hook and modify the values returned by the hook, then return the new values for the next process.

For example when you want to use the_title Filter Hook, which is responsible for generating post title, you must get the title in a parameter, modify it, then return it using PHP return.

Something like this will prepend a text in all post titles:

if(!function_exists('prepend_word_for_titles')){
	function prepend_word_for_titles( $title, $id = null ) {
		return "Article: ".$title;
	}
	add_filter( 'the_title', 'prepend_word_for_titles', 10, 2 );
}

How to work with Filter Hooks in WordPress?

1- Declare the custom function, receive the value, modify, then return it

To modify Data in WordPress, you must create a custom function to get data, modify and then return it.

Let’s do it with an example.

I want to write a function to receive comment text, modify it, then return it.

This will be the function in our functions.php or plugin:

function prepend_word_for_comments( $commentText) {
		return "Commented: ".$commentText;
}

Note: this function will do nothing until we attach it to comment_text Filter Hook.

2- Attach the custom function to a Filter Hook

Now it’s time to attach this custom function we wrote to comment_text Filter Hook.

It’s really easy to do that. We use add_filter function for this matter.

add_filter syntax is like this:

add_filter('filter_hook_name','custom_function_name',priority)

Now we apply this syntax for our custom function:. you can copy/paste this code to see the result in the comments list:

if(!function_exists('prepend_word_for_comments')){
	function prepend_word_for_comments($commentText) {
		return "Commented: ".$commentText;
	}
	add_filter( 'comment_text', 'prepend_word_for_comments', 10 );
}

How to define a custom Filter Hook in WordPress

like Action Hooks, WordPress developers can create custom Filter Hooks.

You can create your own text filter for any text. you have to just apply your filter for those texts using apply_filter function.

Important: if you use add_filter function with a unique filter name (which is not used by WordPress yet), the function will be added as a filter hook in WordPress.

For example, I want to define a function named prepend_word_for_any_text and add it as a filter hook.

This function will receive any text, prepend another text to it, then return it again.

To define this function as a filter, we use this code in your functions.php or plugin:

if(!function_exists('prepend_word_for_any_text')){
	function prepend_word_for_any_text($text) {
		return "Prepended: ".$text;
	}
	add_filter( 'prepend_word_for_any_text', 'prepend_word_for_any_text' );//define filter
}

Because prepend_word_for_any_text is not defined yet, our add_filter will be added as a filter hook in WordPress.

Now it’s time to use our custom filter hook.

To use this filter hook you just need to echo apply_filter anywhere you want:

echo apply_filters("prepend_word_for_any_text","The text");

How to remove Filter Hook

Developers can remove Filters just like adding them. there is a remove_filter function available for this matter.

remove_filter function syntax in WordPress:

remove_filter('filter_name', 'function_name_to_remove');

In the previous example, we prepended a word to all comment texts. no to unhook this function from comment_text filter, you can use this code:

if(!function_exists('prepend_word_for_comments')){
	function prepend_word_for_comments($commentText) {
		return "Commented: ".$commentText;
	}
	add_filter( 'comment_text', 'prepend_word_for_comments', 10 );

	remove_filter( 'comment_text', 'prepend_word_for_comments');//this line is doing the trick
}

+4 examples of WordPress Filter Hooks

Use these practices to learn more about WordPress Filter Hooks:

1- Filter a specific word in post titles

To filter (replace the word with something else) a word in all post titles, developers can use post_title Filter Hook in WordPress.

post_title Filter Hook is responsible to generate the post title for all posts.

in this example, we use ‘test’ word, you can change it to whatever you want.

Full code to filter a specific word:

if(!function_exists('filter_word_in_titles')){
	function filter_word_in_titles( $title, $id = null ) {
		$filterWord = "test";
		return str_replace($filterWord,"***",$title);
	}
	add_filter( 'the_title', 'filter_word_in_titles', 10, 2 );
}

2- Hide commenters names using WordPress Filter Hooks

If you are interested in hiding commenters names in comments list, you can use this code:

if(!function_exists('hide_commenter_name')){
	function hide_commenter_name($author, $comment_ID ) {
		return "";
	}
	add_filter( 'comment_author', 'hide_commenter_name', 10, 2 );
}

3- Change all author names to something specific

This one is easy, just like previous example. you can just do it with a few changes:

if(!function_exists('hide_commenter_name')){
	function hide_commenter_name($author, $comment_ID ) {
		$word = "A great person";
		return $word;
	}
	add_filter( 'comment_author', 'hide_commenter_name', 10, 2 );
}

4- Wrap post titles in h1 tag using Filter Hooks

To do this, you better check if you already added a tag around titles in your theme.

Note: this is just for test, do not execute this codes on a live website.

Use this code to add H1 tags around post titles:

if(!function_exists('add_h1_tag_to_titles')){
	function add_h1_tag_to_titles( $title, $id = null ) {
		return '<h1>'.$title.'</h1>';
	}
	add_filter( 'the_title', 'add_h1_tag_to_titles', 10, 2 );
}

+10 Tips for beginner developers when they want to use WordPress Actions and Filters

1- Always remember the Action and Filter Hooks are the primary ways to connect with WordPress

When you are developing WordPress, there are a few places where you can apply your modifications.

For example, you can edit texts in the places where they are printed, and avoid using Filter Hooks, but think about it for a second…

If you use Filter Hooks to modify Data, you will benefit from advantages.

WordPress Hooks advantages

  • Write once, it will happen everywhere
  • Easy to manage with the order of execution
  • Readability
  • It looks professional

2- Read about Actions and Filters on WordPress official website

WordPress official website is a great source for information.

I know it can sometimes be challenging to understand guidance on official websites (any product really!), but you always can find great help in them.

WordPress official website contains thousands of helpful pages that can help developers to find the correct way of developing this CMS.

Use this page to get started with WordPress:

Getting Started with WordPress on the official website

3- There is a list of hooks on the WordPress official website

For developers, there is a page on WordPress official website that can be the leading page to understanding WordPress Hooks more.

You can visit this page to get more information:

WordPress Hooks on the official website

4- Make a list of interesting WordPress Hooks

There are some WordPress Hooks that you use a lot in your developing time. You better notice these hooks and list them in a notepad (notebook?).

Save interesting hooks in a list and save the working example code with it, in future, you will just copy/past codes to achieve your goals.

5- Make sure you understood the difference between Actions and Filters

If you are not sure you understand the difference between Actions and Filters, you better start this tutorial once again.

For those who need a reminder:

actions are concerned with Events, and filters are concerned with Contents

If you want to fire a function after an Event, you must use Action Hooks.

If you want to edit Content (Data), you must use Filter Hooks.

6- You can do anything with WordPress Hooks, DO NOT feel restricted

WordPress Hooks are easy to use, but they can do a lot!

Developers can use filters to modify WordPress to the core!

They can even modify SQL queries used by WordPress to retrieve or save Data.

You should never feel restricted when you are using WordPress Action and Filters because WordPress creators thought about almost everything you need to modify this CMS.

7- Keep practising with creative ideas

I like those developers who want to learn how stuff works with working examples. Those who want to execute codes and see the result.

If you are a beginner developer, the best way to hack it is to practice it.

In this tutorial, I’ve tried to teach what I learned over the years with working examples, but there are more examples in real projects.

I recommend you to think about some ideas that you can apply them using WordPress Hooks, practice them, try to memorize important ones.

8- Ask your questions on Stackoverflow

Stackoverflow is the best place to ask questions about technical stuff. This website is also a great source of information for developers.

First, search your question in Stackoverflow to check if this issue already been posted or not, then if not, ask it with all information you can give to helpers.

Tell helpers what you’ve tried and what was the result. Good questions will get answers quickly.

Stackoverflow has a special community for WordPress developers, use this link to navigate to this great community:

WordPress Development Stack Exchange

9- Never try to edit WordPress core function directly from files

WordPress core files must always stay untouched.

If you try to modify WordPress core files, you will lose all of your work in the next WordPress update.

It does not matter what you want to do, WordPress made a way for you to achieve that without needing to edit core files.

I advise against editing WordPress core files, even if you think you know what you want to do.

Always remember WordPress Hooks are the means for you to modify WordPress functionality without breaking things or losing codes in the next update.

10- Stay updated and track version changelogs

Even if you are a professional WordPress developer, you must always stay updated.

WordPress is constantly changing, you can track these changes on the WordPress official website.

Read version changelogs carefully, sometimes your codes will be deprecated due to version updates.

What do you think about "WordPress Action and Filter Hooks Tutorial (+10 Examples)"?

Your rating submit was successfull.

Your rating submit was not successfull.

Menu