Essential WordPress plugin hooks

Essential WordPress plugin hooks

Created:17 Jan 2017 11:57:41 , in  Web development

In this article I look at some essential WordPress hooks. By 'essential hooks' I mean actions and filters you use frequently when writing a WordPress plugin. Sometimes in the context of this article 'essential hook' refers to a hook you cannot do without to perform some action.

WordPress Hooks mentioned in this article are: init, wp_loaded, admin_init, admin_enqueue_scripts, admin_menu save_post, get_the_excerpt, wp_trim_excerpt and plugin_action_links.

For simplicity and brevity of code in this article I use PHP lambda functions. It is a good choice for attaching code to hooks but not the best one. In another article I'm going to explain why this is the case.

init

This hook is available for both frontend and backend. As it fires, some important WordPress functionality is loaded already. For example, user is authenticated. At this point you can handle POST or GET requests. This is also popular place to instantiate your plugin.


add_action('init',function(){
  // do stuff here  
});

wp_loaded

This hook, similarly to the previous one, is available for both frontend and admin. Once it fires, both plugins and template have been loaded, also widgets are initialized. You can use is_admin() boolean function to write admin area specific code for it.


add_action('wp_loaded',function(){
  // do stuff here  
});

admin_init

A hook available only for admin area. It's the first one that is run when this area is being accessed by user. Hence, it is a great place to register some admin area code or deal with user access control. This hook fires after init and wp_loaded hooks.


add_action('admin_init',function(){
  // do your admin area initialization stuff here   
});

admin_enqueue_scripts

This hooks is meant for frontend and it is used for adding both stylesheets and scripts to the head of html document. To add scripts / stylesheets to admin area you can use admin_enqueue_scripts hook. For login page you would use login_enqueue_scripts in similar manner.


add_action('wp_enqueue_scripts',function(){
  # enqueue styles.css of the active theme
  wp_enqueue_style( 'style-name', get_stylesheet_uri() );
  # enqeue /js/script.js of the active theme
  wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/script.js', array(), '1.0.0', true );  
});

admin_menu

This hooks is for admin pages only and fires before administration menu is loaded. It is used for registering a function that adds item(s) to Settings item list in admin. The function usually contains a call to add_options_page function in its definition to add page for plugin options.

Suppose you want to add Settings page to Hello Dolly plugin. Using admin_menu in your plugin main file you might do it like this:


add_action('admin_menu',function() {
  add_options_page( 
    'Dolly options', 
    'Dolly', 
    'manage_options', 
     basename(__FILE__),
     'dolly_options_page'
  );   
});

function dolly_options_page() {
	if ( ! current_user_can( 'manage_options' ) )  {
		wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
	}
	echo '<div class="wrap">';
?>
  <form 
     name="<?php echo str_replace('.php','',plugin_basename(__FILE__))?>" 
     method="post" 
     action="<?php echo admin_url('options-general.php?page='.plugin_basename(__FILE__).'&amp;updated=true')?>">
     <?php wp_nonce_field('update-options'); ?>
     <p>Plugin options here </p>
     <?php submit_button(); ?>
  </form>
<?php 
	echo '</div>';
}

save_post

This action is for admin pages only and fires upon saving a post. It is a good place to make an update to custom post meta options for example ( If you need to change how the post will be saved to the database, there is filter called content_save_pre available ).


add_action('save_post', function(){
  // autosave in progress 
  if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
	return;
  }
  
  // 
  if ('post' == $_POST['post_type']) {
    // check if logged in user can edit posts
	if (!current_user_can('edit_post', $post_id)) {
		return;
	}
	// update my_option to new_value 
	update_post_meta($post_id, 'my_option', 'my_option_new_value'));
  }
});

the_content

This is a filter available for frontend. It gives you an opportunity to change content of a post or page after it is fetched from the database and before it is echoed to the page.


add_filter( 'the_content', function($content){
  // do something with $content here
  return $content;
}) 

get_the_excerpt

This filter is used on the frontend and makes it possible to filter post or page excerpt.


add_filter( 'get_the_excerpt', function($excerpt){
  // do something with $excerpt here
  return $excerpt;
}) 

wp_trim_excerpt

Another filter used on the frontend. It make it easy to change trimmed post excerpt before it is displayed.


add_filter('wp_trim_excerpt', 'my_fnc');
function my_fnc($text){
  return '<div class="auto_generated_excerpt">'.$text.'</div>'; 
}

plugin_action_links

This is a filter through which it is possible to modify a plugin default action links array. The links are placed under the plugin name on the plugin list page in admin. By default, the array contains links to 'Activate' or 'Deactivate' ( subject to the plugin being inactive or active ).

If you need extra link, perhaps for the plugin options page, you might add link to one in your plugin file as follows:


add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), 'extra_plugin_links' );
function extra_plugin_links ( $links ) {
 $mylinks = array(
   '<a href="'.admin_url('options-general.php?page='.plugin_basename(__FILE__) ).'">Settings</a>',
 );
return array_merge( $links, $mylinks );
}

I might go on and on on the subject of these essential WordPress hooks, but I guess there is no need anymore. After reading the above, I'm sure, you have some clarity on the subject already. Moreover, what's essential for me might not necessarily be so for you, with this is mind I point you to a page where you'll find a huge (complete ?) list of WordPress hooks. A lot of them have interesting use examples.

WordPress hooks reference page

I hope you have found this article informative and useful.

This post was updated on 25 May 2017 16:17:32

Tags:  php ,  wordpress 


Author, Copyright and citation

Author

Sylwester Wojnowski

Author of the above article, Sylwester Wojnowski, is sWWW admin and owner.He enjoys doing Maths and studying algorithms, writing code in scripting and command languages, Thrash Metal music and playing electric guitar.

Copyrights

©Copyright, 2018 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.

Citation

Cite this article as:

Wojnowski, Sylwester. "Essential WordPress plugin hooks." From sWWW - Code For The Web . https://wojnowski.net.pl//main/index/essential-wordpress-plugin-hooks