Overview #

An important — but often overlooked — best practice is adding custom hooks to your plugin so that other developers can extend and modify it, without having to fork it.

Custom hooks are created and called in the same way that Core’s hooks are, with add_action() / do_action() and add_filter() / apply_filters().

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 bad 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 abcd_email_body¬†(where “abcd” is a unique prefix for your plugin) would avoid any collisions.

Top ↑

Examples #

Creating an Extensible 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. This example shows a custom action being called at the end of the form:

function markup_settings_menu() {
	?>

	Foo: <input id="foo" name="foo1" type="text" />
	Bar: <input id="bar" name="bar1" type="text" />

	<?php

	do_action( 'myplugin_after_form_settings' );
}

So now another plugin can register a callback for the custom myplugin_after_form_settings action and inject new settings:

function add_form_settings() {
	?>

	New 1: <input id="new_setting" name="new_settings" type="text" />
	New 2: <input id="new_setting2" name="new_setting2" type="text" />

	<?php
}
add_action( 'myplugin_after_form_settings', 'add_form_settings' );

Creating an Extensible 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 myplugin_create_post_type() {
	$post_type_params = array( /* ... */ );

	register_post_type(
		'post_type_slug',
		apply_filters( 'myplugin_post_type_params', $post_type_params ),
	);
}

The plugin that wants to modify the post type can then register a callback function for the custom myplugin_post_type_params filter that was created above. In this case, the callback is changing the post type from a flat type to a hierarchical one.

function change_post_type_params( $post_type_params ) {
	$post_type_params['hierarchical'] = true;
	return $post_type_params;
}
add_filter( 'myplugin_post_type_params', 'change_post_type_params' );

Top ↑

External Resources #