Ready! Filter! Action!

Amanda Giles

WordPress Cape Cod - Sept 10, 2019

amandagiles.com/capecod2019

Everything you wanted to know about WordPress Hooks

But were afraid to ask!

We'll cover...

  • What is a hook?
  • Why use hooks?
  • Types of hooks
  • How do they work?
  • Syntax
  • Examples
  • Creating custom hooks
  • Checking for and removing hooks
  • Reference Links

Who am I?

  • Programmer since 1985 (Basic & Logo!)
  • Made my first website in 1994
  • Professionally coding for over 20 years
  • Independent Consultant since 2006
  • Working with WordPress since 2009
  • Started the Seacoast NH WordPress Meetup in 2011
  • Co-Created Spark Development (WordPress Development Agency) in 2016

What is a hook?

A hook is an "event" or a "point in time" within WordPress code which allows for additional code to be run when it occurs.

 

Developers of WordPress core, plugins, and themes create hooks in their code at specific points for other developers to "hook into".

Last Call is a real life "Action Hook"

More about Hooks...

One or more functions can be associated with a hook and they will all run when the hook is triggered.

 

Those functions can be given a priority to control the order in which they run (default priority is 10).

Why use hooks?

Hooks are placed within WordPress core, plugins, and themes to allow customization by other developers without direct edits of the code.

 

Hooks are the proper way to alter the default behavior of code which is not yours to edit.

2 Types of hooks

Action hooks allow you to run code at a certain point within the code.

Examples in WP core include initialization, before main query is run, header or footer of a page/post.

 

Filter hooks are exactly like action hooks, but also allow you to alter information (content, parameters, etc).

A filter hook is passed information and can return it altered (or not!).

Examples in WP code include displaying content, page/post title, or before saving content (admin).

How do action hooks work?

Action hooks are triggered by do_action()

do_action('wp_logout');

 

And they are "hooked" into using add_action()

add_action('wp_logout','clear_session_data');

 

function clear_session_data() { 
    $_SESSION['customerid'] = '';
    $_SESSION['cart'] = array();
}

Syntax of action hooks

Action hooks are created by calling do_action() with a hook name and optional extra arguments which are then passed to "hooking" function(s).

do_action($hookname);
do_action($hookname, $arg_a, $arg_b, $arg_c);

 

"Hook" your function by calling add_action() in your code

add_action( $hookname, $function_name, $priority, $num_args );
  • $hookname : the name of the action hook
  • $function_name : name of the function to hook in
  • $priority : Specify order precedence, default = 10  (Optional)
  • $num_args : (Optional) Specify # of arguments, default =1  (Optional)

How do filter hooks work?

Filter hooks are triggered by apply_filters()

$excerpt_length = apply_filters( 'excerpt_length', 55 );

 

And they are "hooked" into using add_filter()

function custom_excerpt_length( $length ) {
	return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

Syntax of filter hooks

Filter hooks are created by calling apply_filters() with a hook name, an initial value, and optional extra arguments to pass to "hooking" function(s).

Note: The value returned by apply_filters() must be captured.

$newvalue = apply_filters( $hookname, $value );
$newvalue = apply_filters( $hookname, $value, $arg_a, $arg_b );

 

And they are "hooked" into using add_filter()

add_filter( $hookname, $function_name, $priority, $num_args );
  • $hookname : the name of the action hook
  • $function_name : name of the function to hook in
  • $priority : Specify order precedence, default = 10  (Optional)
  • $num_args : (Optional) Specify # of arguments, default =1  (Optional)

Note: If $num_args is not specified, then only $value will be passed.

Let's see Hooks in action

Action Hook Example

add_action('wp_enqueue_scripts', 'my_enqueue_styles');

function my_enqueue_styles() {    
    //Enqueue parent theme style
    wp_enqueue_style( 
       'parent-style', 
       get_template_directory_uri() . '/style.css' );

    //Enqueue Google's Cabin Font
    wp_enqueue_style( 
       'google-cabin-font', 
       '//fonts.googleapis.com/cssfamily=Cabin:400,600,700');
}

Action Hook Example

add_action( 'wp_footer', 'add_footer_scripts' );

 

function add_footer_scripts() { ?>
   <script charset="utf-8"   
      ​type="text/javascript">stLight.options({
      "publisher":"25f2ecb3-8176-af3d-c835c06767ad",  
      "doNotCopy":false,
      "hashAddressBar":true,
      "doNotHash":false});
      var st_type="wordpress4.0";
   </script>
<?php }

Filter Hook Example

//Replace 'Trump' with 'Drumpf'
add_filter('the_content', 'replace_trump_drumpf' );

function replace_trump_drumpf( $content ) {
     $content = str_replace( 'Trump', 'Drumpf', $content);
     return $content;
}

Filter Hook Example

//Link Widget title to Blog page
add_filter('widget_title', 'link_posts_widget_title');

function link_posts_widget_title( $title ) {
   if ($title == 'Blog' ) {
      $title = '<a href="/blog/">' . $title . '</a>';
   }
   return $title;
}

pre_get_posts()

pre_get_posts() is a hook which occurs after the $query object is created, but before that query is run. 

 

NOTE: This seems like it should be a filter hook because you are altering the $query arguments, but it's actually an action hook which passes the $query object by reference so that changes made within your hooked function are saved without needing to return any values from the function.

pre_get_posts() Hook Example

add_action('pre_get_posts', 'cats_home_filter_posts'); 

function cats_home_filter_posts( $query ) { 
    // Make sure we're only affecting the main query on home page
    if ( is_main_query() && is_home()) {
            //On home page, show only 'cats' posts
            $query->set('category_name', 'cats');
            //Show *all* the 'cats' posts
            $query->set('posts_per_page', -1);           
    }
}

Creating custom hooks

When creating themes and plugins, you can create your own hooks by placing do_action() and apply_filters() calls at appropriate points in your code.

 

Be sure to make the names unique by adding a prefix related to your theme or plugin to the name of the hook. This will help to avoid conflicts with other hooks (although it's not foolproof).

 

do_action('myplugin_before_widget');
apply_filters('myplugin_widget_title', $title);

Finding hooks

Find hooks by searching code for do_action() and apply_filters() calls in WordPress core or plugins.

 

Both action and filter hooks can be called with additional parameters, so it's helpful to look up how the hooks are called.

 

Using an IDE can help you easily locate hooks. By exploring the definition of existing core or plugin functions, you can see what's available for hooks.

Hook related functions

Here are some other functions related to action and filter hooks:

has_filter( $hookname, $function_to_check )
has_action( $hookname, $function_to_check )
current_filter()
doing_filter( $hookname = NULL)
doing_action( $hookname = NULL) 
did_action( $hookname )
remove_filter( $hookname, $function_to_remove, $priority )
remove_action( $hookname, $function_to_remove, $priority )
remove_all_filters( $hookname, $priority)
remove_all_actions( $hookname, $priority)

Reference Material

 And now you know enough to get into your own mischief with hooks! 

Thank you!

Ready! Filter! Action!

By Amanda Giles

Ready! Filter! Action!

One of the most powerful (and proper) ways to modify WordPress core, theme, or plugin behavior is through the use of action and filter hooks. This presentation explains what hooks are and how to use them to effectively alter the default behavior of WordPress core, themes, or plugins to do our bidding.

  • 1,735