Hooks in WordPress allow developers to easily tie their own code in with the WordPress core code base, themes, and plugins. In this article, we’ll discover what hooks are, go over the different types of hooks, and look at a few examples of hooks in action.
Contents
Definition of Terms
A Hook is a generic term in WordPress that refers to places where you can add your own code or change what WordPress is doing or outputting by default. Two types of hooks exist in WordPress: actions and filters.
An Action in WordPress is a hook that is triggered at specific time when WordPress is running and lets you take an action. This can include things like creating a widget when WordPress is initializing or sending a Tweet when someone publishes a post.
A Filter in WordPress allows you get and modify WordPress data before it is sent to the database or the browser. Some examples of filters would include customizing how excerpts are displayed or adding some custom code to the end of a blog post.
At first, it may be a little confusing to figure out whether something is an action or a filter. The important difference is that when you work with a filter, you are going to receive some piece of data and then, at the end of your function, you have to return that data back. With an action, on the other hand, you are not receiving and modifying data, you are simply given a place in the WordPress runtime where you can execute your code.
Related Reading: The Perfect WordPress Inline SVG Workflow
Action and Filter Hooks
The WordPress Codex has two important pages that can help you orient yourself with what hooks are available in WordPress.
NOTE: At the time of writing there is a bit of a transition of documentation on hooks from the Codex to the Code Reference site. Because of this you may find hooks that are listed on the Codex, but not documented. You should be able to find some documentation for all of the hooks if you search for them in the Code Reference, however, it does not have any current pages like the Codex where all hooks are grouped in one place.
The WordPress Action Reference page has available actions listed by the following categories:
- Actions Run During a Typical Request
- Actions Run During an Admin Page Request
- Post, Page, Attachment, and Category Actions (Admin)
- Comment, Ping, and Trackback Actions
- Blogroll Actions
- Feed Actions
- Template Actions
- Administrative Actions
- Dashboard “Right Now” Widget Actions
The Codex also has a similar Filter Reference page, which it lists by the following categories:
- Post, Page, and Attachment (Upload) Filters
- Comment, Trackback, and Ping Filters
- Category and Term Filters
- Link Filters
- Date and Time Filters
- Author and User Filters
- Blogroll Filters
- Blog Information and Option Filters
- General Text Filters
- Administrative Filters
- Rich Text Editor Filters
- Template Filters
- Registration & Login Filters
- Redirect/Rewrite Filters
- WP_Query Filters
- Media Filters
- Advanced WordPress Filters
- Widgets
- Admin Bar
Many of these filter hooks are separated into subcategories: Database Reads and Database Writes. This depends on whether you are reading from the database prior to displaying on a page or editing a screen, or you are writing code prior to saving data to the database.
Working with hooks in WordPress starts with figuring out what hook you need to tie your code into and then writing the code to modify the data you need or run whatever action you need.
If you get stuck or you are not sure which hook to use, you can usually figure it out by searching for something like: “WordPress action for [whatever you want to hook into].” The WordPress StackExchange has a number of results with questions like this as well.
How to Add and Remove Your Own Functions
If you would like to hook in your own functions, the process is quite simple. You first need to know a few pieces of information. For actions, you’ll want to know the name of the hook, as well as when exactly it runs. For filters, you also need to know the name of the hook, but you want to know what value you are going to get and have to return, as well. The final bit of information you need is the name of the function where you have all your code.
How to Hook into an Action
add_action( $hook, $function_to_add, $priority, $accepted_args );
The required parameters of the add_action function are the hook and function to add. The priority is an optional integer value based on a scale of 1 to 999 that determines the priority of order for functions tied to that specific hook. Higher priority means it runs later, lower priority means earlier. The last parameter is used less often and it is for when you need to pass or accept multiple arguments.
How to Hook into an Filter
add_filter( $tag, $function_to_add, $priority, $accepted_args );
The add_filter works the same way as add_action. You will also have to be careful because sometimes a hook exists as both an action and a filter, or a filter and a function. You will see the real difference with the actual function you call.
Remember that, for a filter, the function_to_add both receives a value and has to return it at the end of the function. Actions, on the other hand, simply run the code they need to and don’t return a value.
How to Unhook from Actions and Filters
To remove a hook is quite simple. Use the function remove_action or remove_filter along with the name of the hook, function, and priority. The priority is optional and helpful if you have to unhook a function that is hooked more than once and you only want to remove a specific occurrence of that function.
remove_action( $tag, $function_to_remove, $priority );
remove_filter( $tag, $function_to_remove, $priority );
Now that we have looked at the basics of how functions are hooked and unhooked, let’s take a look at a few real world examples of some different hooks in action.
Examples of WP Hooks
More than 200 hooks exist in WordPress. Below you will find a few examples of common hooks in use.
Register a Custom Menu in the Admin
function register_my_custom_menu_page() { add_menu_page( 'custom menu title', 'custom menu', 'manage_options', 'myplugin/myplugin-admin.php', '', 'dashicons-admin-site', 6 ); } add_action( 'admin_menu', 'register_my_custom_menu_page' );
In the example above you can see the function register_my_custom_menu_page being hooked into the admin_menu action hook. This allows you to run code when the admin menu is being generated. This is most commonly used to add a custom menu link for a plugin or theme.
Related Reading: Create Your First WordPress Custom Post Type
Change the Excerpt Length
function excerpt_length_example( $words ) { return 15; } add_filter( 'excerpt_length', 'excerpt_length_example' );
In this example, we are using the excerpt_length filter, which provides us with an integer that determines the length used with the_excerpt(). If you are unsure about what value is passed to a filter, you can search the WordPress core code for apply_filters( ‘filter_name’ and look deeper into what is going on with that filter.
Hook into Post Publishing
function publish_post_tweet($post_ID) { global $post; // Code to send a tweet with post info } add_action('publish_post', 'publish_post_tweet');
In the pseudo example above, you can see that we are hooking into an action called “publish_post” which runs when a post is published. You could use this to do something like sending a tweet with information about the published post.
The actual code for this is more complex than we have space to cover, but it serves as a good example of an action you can run when a post is published.
Hook Into Widget Initialization
function create_my_widget() { register_sidebar(array( 'name' => __( 'My Sidebar', 'mytheme' ), 'id' => 'my_sidebar', 'description' => __( 'The one and only', 'mytheme' ), )); } add_action( 'widgets_init', 'create_my_widget' );
Creating a widget is a very simple and common action to add to a theme or plugin. When you do so, you have to hook into the widget_init action. This hook lets you run your code when widgets are being generated within WordPress, so it’s the perfect hook to add your own widgets at the same time.
Hook Into Front-end Scripts and Styles
function theme_styles() { wp_enqueue_style( 'bootstrap_css', get_template_directory_uri() . '/css/bootstrap.min.css' ); wp_enqueue_style( 'main_css', get_template_directory_uri() . '/style.css' ); wp_enqueue_script( 'bootstrap_js', get_template_directory_uri() . '/js/bootstrap.min.js', array('jquery'), '', true ); wp_enqueue_script( 'theme_js', get_template_directory_uri() . '/js/theme.js', array('jquery', 'bootstrap_js'), '', true ); } add_action( 'wp_enqueue_scripts', 'theme_styles' );
This is a commonly-used hook and one that you learn quite early in WordPress development. It allows you to generate a URL stylesheets and JavaScript files on the front-end of your theme. This is the preferred method of linking to CSS and JS, rather than hardcoding the links in your theme header.
Dig Deeper Into Hooks
This article serves as a very basic introduction to working with hooks in WordPress. If you would like to go deeper, I suggest checking out my course on WordPress Hooks – Actions and Filters, now available at Treehouse!
To improve your coding skills, check out the Treehouse 7-day free trial!
Hi there to every single one, it’s truly a good for me to pay a visit this web
page, it consists of priceless Information.
hi, can we hook directly my setting page from another theme setting without touching any code.
Having read this I thought it was really enlightening.
I appreciate you finding the time and effort to put this
article together. I once again find myself spending a
significant amount of time both reading and leaving comments.
But so what, it was still worthwhile!
Hello Zac Gordon,
Thank you for this awesome tutorial. My doubt on hook is :
What is advantage of using hook over defining function with if ( ! function_exist() ) while customizing parent function on child theme. Here is the example:
This code on parent functions.php template:
if ( ! function_exist( ‘your_function_name’ ) ) :
function your_function_name() {
//code goes here
}
endif;
To overwrite on child theme i can simply defined this function and make changes:
But while i use hook on the same instance i need to first remove the hook and write my custom code.
I look forward for your response.
Thanks
Thank for categorize WordPress filters, it help me easy to search and learn. I think it’s better if you have code examples for each filters 😀
Great resource. Will dig deeper.
Good article, i need how to implement or write hooks and conditional functions in plugin boilerplate.I have downloaded plugin from plugin boilerplate i don’t know how to move to develop a plugin as a beginner of WP plugin developer by using plugin boilerplate. i need step by step procedure to implement code(hooks & functions) in plugin boilerplate as per example requirement.
thanking you.
Hi there! This would be a good question to ask in the Treehouse Community, where our teachers and students are always happy to help and share their feedback.
This has been so helpful, thanks! I have been busting my brain cells trying to work out how to add actions into existing hooks all week!! The documentation for the parent theme I am writing a child theme for is pretty poor, I am shocked as its a reputable developer. I have also been taking your WordPress – hooks course on treehouse. Finally getting somewhere. Still need more practice, other than the ones you have mentioned do you have any other resources / articles that you would recommend? Thanks again and thanks for bringing out so many great WordPress courses. Please keep them coming!
Hi Ashley! Great to hear you benefited from the post and that you’re learning with us! If you’d like to check out all the WordPress content we have available on the blog, search “WordPress” and we’ll filter the posts for you. Keep up the great work! 🙂
Just amazing explanation, helped a lot
Excellent article on Hooks. It is first time I am reading hooks.I will try to write first plugin.
I am satisfied that you shared this useful information with us. Please keep us up to date like this.
WordPress is still awesome to use. More than 17,00 plugins and great SEO techniques used. Other CMS’s are giving a good fight with it. But no other CMS can ease the use unlike WordPress.
It’s actually a nice and useful piece of information. I am satisfied that you shared this useful information with us. Please keep us up to date like this. Thank you for sharing.
Thank you so much! It helps a lot.
Using the Widget code I think!
This has been really helpful. I’m trying to write a plugin for a sign makers in sheffield. This could be the key!!