Custom Hooks

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

To create a custom hook, use do_action() for Actions and apply_filters() for Filters.

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.

Top ↑

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.

Top ↑

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.

Top ↑


Top ↑

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.

    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:

    New 1:
add_action( 'wporg_after_settings_page_html', 'myprefix_add_settings' );

Top ↑

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.

function wporg_create_post_type()
    $post_type_params = [/* ... */];

        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:

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' );

Top ↑

External Resources