What is a WordPress Hook

What is a WordPress Hook? In WordPress development, Hooks make up the foundation for how plugins and themes interact with the WordPress Core. Hooks are functions used to interact/modify another piece of code at specific, pre-defined spots. These can be used by plugin and theme developers to change the default WordPress functionality.

There are two types of Hooks in WordPress which are Actions and Filters. To use either type of Hook, you’ll need to write a custom function called a callback and register it with a Hook for a specific Action or Filter. Although Actions and Filters are similar, they are not the same.

How do WordPress Actions Work?

A WordPress Action lets developers execute code at specific points throughout the WordPress core. An Action takes the info it receives, does something with it, and returns nothing. So, a WordPress Action executes something at a specific place.

// Load custom javascript file
function load_custom_script(){
	wp_register_script( 'custom-js', custom.js', false );
	wp_enqueue_script( 'custom-js' );
}
add_action( 'wp_enqueue_scripts', 'load_custom_script' );

The sample code above creates a function load_custom_script which is hooked into wp_enqueue_scripts action.

How do WordPress Filters Work?

A WordPress Filter allows you to make modifications to functions in the WordPress core. A Filter takes the info it receives, modifies it, and returns the new version. So, a WordPress Filter modifies something and returns it.

// Create a custom excerpt length
function custom_excerpt_length( $length ) {
   return 20;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );

The sample code above creates a function custom_excerpt_length which is hooked into excerpt_length.

Additional Reading: