Useful WordPress plugin snippets

Posted: July 23rd, 2011 | Tags: , , | No Comments »

In developing a WordPress plugin, I’ve been pleasantly surprised by the documentation. The codex is through, and links to the source code in the cases when it’s not deep. Having said there, there were a few snippets of code that took some searching to find and explain – common things that almost all plugins will (should) use, but weren’t obviously listed.

Activation/Deactivation Hooks

register_activation_hook( __FILE__, 'fn_activation' );
register_deactivation_hook( __FILE__, 'fn_deactivation' );
function fn_activation() { ... }
function fn_deactivation() { ... }

Used to run code when the plugin is activated and deactivated. First argument is a path to the main plugin file (where this code should be), second is the name of the function to be run. Hooking to register_activation_hook is an easy way to save defaults of user-selectable options into the database. The codex discusses them here, and have a read of this if you’re looking to have some code run when a user uninstalls your plugin (it’s slightly more subtle than just a function hook).

Contextual Help

add_filter( 'contextual_help', 'fn_contextual_help_handler', 10, 3 );
function fn_contextual_help_handler( $c_help, $screen_id, $screen ) {
	global $menu_hook_name;

	if( $screen_id == $menu_hook_name )
		$c_help= "YOUR TEXT HELP HERE";

	return $c_help;
}

Every screen in the WordPress administration menu has a contextual help option (it’s at the top right of the window) – this allows you to customize the text to something relevant to your plugin. $menu_hook_name needs to be the return value of add_options_page(), to identify on which page your help should be shown. Discussed in the codex here.

Adding a ‘Settings’ Option to the Plugin Listing

add_filter( 'plugin_action_links', 'add_action_link', 10, 2 );
function add_action_link( $links, $file ){
	static $this_plugin;

	if( ! $this_plugin ) {
		$this_plugin = plugin_basename( str_replace( '-admin', '',
			__FILE__ ) );
	}

	if( $file == $this_plugin ) {
		$settings_link = '<a href="' . get_bloginfo( 'wpurl' ) .
			'/wp-admin/options-general.php?' .
			'page=ADMIN_PAGENAME">Settings</a>';
		array_unshift( $links, $settings_link );
	}
	return $links;
}

The plugin page, by default, only lists Activate/Deactivate and Edit actions for each one listed. If you’d like to add an action to your listing – like a direct link to your plugin’s settings page, for example, you can use this. Lines 3 to 8 are used to avoid having to keep calling plugin_basename() – if you’d like to simplify it, you can eliminate that section and replace it with a hardcoded path to your plugin’s main file. $settings_link is what will be added to the plugin listing – in this case, it’s a link to the settings page. Adapted from here.



Leave a Reply