WordPress - pxlshpr/knowledge-base GitHub Wiki

WordPress

TL;DR – Actions vs Filters

  • Actions
    • When something has to be added
    • declared with add_action()
    • used with do_action()
  • Filters
    • When something has to be changed
    • declared with apply_filters()
    • used with add_filters()

From Zell's blog

Hooks

  • WordPress hooks refer to two things – actions and filters.

  • In a broad sense, hooks enable us to literally hook into parts of the WordPress page lifecycle to retrieve, insert, or modify data, or they allow us to take certain actions behind the scenes.

Actions

  • The simplest definition of an action is that they indicate that something has happened.

  • They are basically certain points during the WordPress lifecycle in which you can introduce your own functionality. So, you have the ability of making something happen while a page is loading.

  • The fundamental thing with actions is understanding the order in which they fire and hooking at the appropriate point during the execution.

    For e.g. Novice developers would often hook into the init action far too often. There are times when this is actually appropriate – but, say you wanted to do something just before getting the posts, then pre_get_posts would be the more relevant hook for this.

Filters

  • Filters are similar to actions in that they occur at different points during the WordPress page lifecycle.

  • Unlike actions though, filters are functions that WordPress passes data through during certain points of the page lifecycle.

    They are primarily responsible for intercepting, managing, and returning data before rendering it to the browser or saving data from the browser to the database.

  • Take the example of a site visitor loading a post.

    • From the WordPress page lifecycle, it would query the database for the post, then return it to the browser.
    • Before doing that though, it runs the data through any filters that have been established – which are meant to take action on data that's being passed to them.
    • For example, if you wanted to append a short sentence about the author at the end of the content, you'd register a custom function with the the_content filter and append your sentence to the content.

Choosing which hook to use

  • Use actions when you want to add something to the existing page without dealing with any data from the backend. For instance:
    • Stylesheets
    • JavaScript dependencies
    • Sending an email when an event has happened
  • Use filters when you want to manipulate data coming out of the database prior to going to the browser, or vice versa.