How to use a custom hook

The problem is the order of execution. The order things run matters.

For your code to function, it would require either add_action to implement time travel several microseconds into the past so that it can add the hook before it ran, or it would require do_action to implement precognition so that it knows about add_action calls in the future that have not happened yet.

By putting your add_action call in home.php or other templates that occur after the header.php runs, you are telling WordPress to execute code when a hook fires that has already fired.

It is the equivalent to arriving at an airport and trying to board a flight that has already left.

You need to add the actions before the action runs.

A useful mental model is to think of actions as events. When you specify add_action of add_filter it is the same as saying “from now on, when this action runs, do this”.

This is also why you do not see themes add filters and actions inside template files. These go in plugins and functions.php because those files are loaded earlier.