Adding function directly vs using hook in function.php

Imagine 2 people are cooking food, and both are following a recipe, when both reach instruction 5. This instruction tells them what to do with some uncooked meat that may be dangerous to eat uncooked.

In Alices‘s cookbook she sees:

When the meat is safely cooked, eat the meat

In Bobs‘s cookbook he sees:

eat the meat

Alice cooks the meat and goes home with a full stomach.

Bob eats uncooked meat, and is rushed to A&E several hours later with E coli poisoning.

A similar case is true of hooks and filters. By using a hook to do work, you’re specifying when that work happens. By putting it straight in the functions.php file, it will happen as soon as the file is loaded, and that isn’t always appropriate. Perhaps something hasn’t been loaded yet? Or something must happen last or as early as possible?

A week later, person C and D attempt to follow the first recipe, both are using a revised recipe with a 6th step. They heard what happened to Bob and decided to makes some modifications.

Person C sees:

6: when you have friends around, add expensive sauce

Person D sees:

6: add expensive sauce

Expensive sauce is very expensive, there are only 5 bottles of it! Neither person has friends, so Person C saves money by not using sauce. But Person D always adds expensive sauce, even when it isn’t needed, because their recipe doesn’t specify when it should and shouldn’t be added.

This is also true of hooks. Sometimes you only want things to happen when certain events occur, etc For example, I might perform a check on the admin_init hook, this way the check does not occur on the frontend, only the dashboard admin

Leave a Comment