WordPress Tutorial
Lesson 42 of 50 (84%)
84% Complete

WordPress Actions and Filters

Learn how to use WordPress action and filter hooks to add functionality, customize website behavior, and modify content using PHP.

Learning Objective: Understand action and filter hooks, use add_action() and add_filter(), work with hook priorities and callback arguments, and create practical WordPress customizations.

1. What Are Actions and Filters?

WordPress provides a hook system that allows developers to extend functionality without modifying WordPress core files. The two main types of hooks are actions and filters.

Action Hooks

Actions allow you to execute custom code at a particular point during WordPress execution.

Function: add_action()

Filter Hooks

Filters allow you to receive a value, modify it, and return the updated value.

Function: add_filter()

2. Understanding add_action()

The add_action() function registers a callback function to run when a particular action hook is executed.

Syntax

add_action() Syntax
add_action(
    $hook_name,
    $callback,
    $priority,
    $accepted_args
);

Parameters:

Parameter Description
$hook_name Name of the action hook.
$callback Function that should run.
$priority Controls the order of execution. Default is 10.
$accepted_args Number of arguments accepted by the callback. Default is 1.

3. Practical Example of an Action

Let's display a welcome notice in the WordPress administration area.

Example: Admin Welcome Notice
<?php

function soopro_admin_notice() {

    echo '<div class="notice notice-success is-dismissible">';
    echo '<p>Welcome to Soopro WordPress Tutorials!</p>';
    echo '</div>';

}

add_action(
    'admin_notices',
    'soopro_admin_notice'
);

How it works:

  1. soopro_admin_notice() is the custom function.
  2. admin_notices is the WordPress action hook.
  3. add_action() connects the function to the hook.
  4. WordPress runs the function when it triggers the hook in the admin area.
Add this example to a custom plugin or your child theme's functions.php file. Avoid adding the same function more than once, because duplicate function declarations can cause a PHP fatal error.

4. Understanding add_filter()

The add_filter() function registers a callback that can modify a value passed through a filter hook.

Syntax

add_filter() Syntax
add_filter(
    $hook_name,
    $callback,
    $priority,
    $accepted_args
);

5. Practical Example of a Filter

We can use the excerpt_length filter to change the default number of words used when WordPress generates an excerpt.

Example: Change Excerpt Length
<?php

function soopro_excerpt_length($length) {

    return 25;

}

add_filter(
    'excerpt_length',
    'soopro_excerpt_length'
);

Explanation:

  • excerpt_length is the filter hook.
  • $length receives the current length value.
  • return 25; returns the new value.
  • WordPress uses the filtered length when generating the excerpt.
The final appearance of an excerpt depends on how the theme or plugin generates and displays it.

6. Difference Between Actions and Filters

Feature Actions Filters
Purpose Run custom code. Modify data.
Registration function add_action() add_filter()
Typical callback behavior Perform a task. Return a value.
Example hook admin_notices the_title
Common use Load scripts or display notices. Change titles or excerpts.

7. Example: Modify a Post Title

The the_title filter lets you modify a post or page title as WordPress processes it.

PHP Code
<?php

function soopro_modify_title($title, $post_id) {

    if (is_admin()) {
        return $title;
    }

    if (get_post_type($post_id) !== 'post') {
        return $title;
    }

    if (!in_the_loop() || !is_main_query()) {
        return $title;
    }

    return 'Tutorial: ' . $title;

}

add_filter(
    'the_title',
    'soopro_modify_title',
    10,
    2
);

What happens?

For applicable blog post titles processed in the main query loop, the returned title begins with Tutorial:. The conditions help avoid modifying titles in the admin area or unrelated contexts.

The the_title filter can run in different contexts. Always test title filters with your active theme and plugins to avoid unintended changes.

8. Hook Priority

Priority controls the order in which callbacks attached to the same hook run. A lower priority number runs earlier than a higher number.

Example
<?php

function soopro_first_task() {
    // First task
}

function soopro_second_task() {
    // Second task
}

add_action(
    'init',
    'soopro_first_task',
    5
);

add_action(
    'init',
    'soopro_second_task',
    20
);

When the init action runs, the first callback is scheduled to run before the second callback because its priority is lower.

9. Passing Arguments to Hooks

Some hooks pass additional information to callback functions. You can specify how many arguments your callback accepts.

Example: Receive the Post ID
<?php

function soopro_after_save_post($post_id, $post, $update) {

    if (wp_is_post_revision($post_id)) {
        return;
    }

    if ($post->post_type !== 'post') {
        return;
    }

    // Add your post-save task here.

}

add_action(
    'save_post',
    'soopro_after_save_post',
    10,
    3
);

Explanation:

  • $post_id identifies the saved post.
  • $post contains the post object.
  • $update indicates whether an existing post is being updated.
  • The fourth argument of add_action() is set to 3 so the callback accepts all three arguments.
Hooks such as save_post can run in multiple situations. Production code should account for revisions, autosaves, post types, permissions, and other conditions relevant to the task.

10. Removing an Action or Filter

WordPress also provides functions to remove callbacks that were previously registered with a hook.

remove_action()
remove_action(
    'admin_notices',
    'soopro_admin_notice'
);
Removes the specified callback from an action hook when the callback and priority match its registration.
remove_filter()
remove_filter(
    'excerpt_length',
    'soopro_excerpt_length'
);
Removes the specified callback from a filter hook when the callback and priority match its registration.

The removal must happen after the callback has been registered and before the relevant hook executes. If the original callback uses a non-default priority, pass that same priority when removing it.

11. Common WordPress Hooks

Hook Type Purpose
init Action Run code during WordPress initialization.
wp_enqueue_scripts Action Enqueue front-end scripts and styles.
admin_notices Action Display notices in the admin area.
save_post Action Respond to post-save events.
the_title Filter Modify post or page titles.
the_content Filter Modify post content during content processing.
excerpt_length Filter Change the default excerpt word length.
body_class Filter Modify body CSS classes.

12. Where Should You Write Hook Code?

Child Theme
Use the child theme's functions.php for functionality related to your active theme.
Custom Plugin
Use a custom plugin when the functionality should continue working after you change themes.

13. Best Practices

Important Tips
  • Do not modify WordPress core files.
  • Use unique names for custom functions.
  • Return modified data from filter callbacks.
  • Check the number and meaning of callback arguments.
  • Choose hook priorities carefully.
  • Escape output and validate user-provided data.
  • Test customizations on a development website first.

14. Practical Assignment

Your Task
  1. Create a child theme or custom plugin.
  2. Display an admin notice using add_action().
  3. Change the excerpt length using add_filter().
  4. Modify a post title with the the_title filter.
  5. Experiment with hook priorities.
  6. Remove a registered callback using remove_action() or remove_filter().
  7. Explain the difference between actions and filters in your own words.

15. Lesson Summary

  • Actions execute code at particular points in WordPress.
  • Filters modify data and return the updated value.
  • add_action() registers an action callback.
  • add_filter() registers a filter callback.
  • Priority controls callback execution order.
  • The accepted-arguments parameter controls how many hook arguments a callback receives.
  • remove_action() and remove_filter() remove registered callbacks.

Lesson 42 Quiz: WordPress Actions and Filters

Choose the correct answer for each question.

1. Which function registers an action callback?

2. What should a filter callback normally return?

3. What does hook priority control?