Skip to content

Using Hooks and Filters

Hooks let you customize WordPress (and your theme) without editing core files. There are two types:

  • Actions: run code at a specific moment (e.g., enqueue scripts).
  • Filters: modify a value before it is used (e.g., change excerpt length).

Where to put hook code

Use one of these locations so updates do not overwrite your changes:

  • Child theme: add code to functions.php.
  • Code Snippets plugin: best for quick tests or small tweaks.
  • Custom plugin / mu-plugin: best for site-wide logic that should not depend on a theme.

Action example

<?php
add_action('wp_enqueue_scripts', function (): void {
    wp_enqueue_style(
        'my-custom-overrides',
        get_stylesheet_directory_uri() . '/custom.css',
        [],
        '1.0.0'
    );
}, 20);

Filter example

<?php
add_filter('excerpt_length', function (int $length): int {
    return 18; // 18 words instead of default 55
});

Priority and arguments

Hooks can accept a priority (lower runs first) and the number of arguments:

<?php
add_action('init', 'my_custom_init', 20, 0);

function my_custom_init(): void
{
    // Custom logic here
}

Remove an existing hook

If you need to stop a default behaviour, remove the hook that adds it:

<?php
remove_action('wp_head', 'wp_generator');

Best practices

  • Always prefix your function names to avoid collisions.
  • Keep changes small and focused (one hook = one purpose).
  • Prefer a child theme or custom plugin over editing the parent theme.
  • Test changes on a staging site first.