Custom Hooks
Topics
An important, but often overlooked practice is using custom hooks in your plugin so that other developers can extend and modify it.
Custom hooks are created and called in the same way that WordPress Core hooks are.
Create a Hook Create a Hook
To create a custom hook, use do_action() for Actions and apply_filters() for Filters.
Note:
We recommend using apply_filters() on any text that is output to the browser. Particularly on the frontend.
This makes it easier for plugins to be modified according to the user’s needs.
Add a Callback to the Hook Add a Callback to the Hook
To add a callback function to a custom hook, use add_action() for Actions and add_filter() for Filters.
Naming Conflicts Naming Conflicts
Since any plugin can create a custom hook, it’s important to prefix your hook names to avoid collisions with other plugins.
For example, a filter named email_body
would be less useful because it’s likely that another developer will choose that same name. If the user installs both plugins, it could lead to bugs that are difficult to track down.
Naming the function wporg_email_body
(where wporg_
is a unique prefix for your plugin) would avoid any collisions.
Examples Examples
Extensible Action: Settings Form Extensible Action: Settings Form
If your plugin adds a settings form to the Administrative Panels, you can use Actions to allow other plugins to add their own settings to it.
<?php function wporg_settings_page_html() { ?> Foo: <input id="foo" name="foo" type="text"> Bar: <input id="bar" name="bar" type="text"> <?php do_action('wporg_after_settings_page_html'); }
Now another plugin can register a callback function for the wporg_after_settings_page_html
hook and inject new settings:
<?php function myprefix_add_settings() { ?> New 1: <input id="new_setting" name="new_settings" type="text"> <?php } add_action('wporg_after_settings_page_html', 'myprefix_add_settings');
Extensible Filter: Custom Post Type Extensible Filter: Custom Post Type
In this example, when the new post type is registered, the parameters that define it are passed through a filter, so another plugin can change them before the post type is created.
<?php function wporg_create_post_type() { $post_type_params = [/* ... */]; register_post_type( 'post_type_slug', apply_filters('wporg_post_type_params', $post_type_params) ); }
Now another plugin can register a callback function for the wporg_post_type_params
hook and change post type parameters:
<?php function myprefix_change_post_type_params($post_type_params) { $post_type_params['hierarchical'] = true; return $post_type_params; } add_filter('wporg_post_type_params', 'myprefix_change_post_type_params');
External Resources External Resources
- Extendable Extensions by Michael Fields
- WordPress Plugins as Frameworks by Josh Harrison
- The Pluggable Plugin by Brandon Dove
- WordPress Plugin Pet Peeves #3: Not Being Extensible by Will Norris