When you want to add a simple function to your WordPress, you can place it almost anywhere, and it will work.

Every time you load a page on a WordPress site, WordPress executes many different things, and they follow an order, but the order when some code is executed doesn’t depend on where it’s placed.

For example, it makes some setup, then initialises, and later loads the template of the page. There are hundreds of in-between steps called hooks.

A hook is a place on the list of things WordPress does every time it’s loaded. And depending on how you are loading it, some hooks will be added or removed.

For example, if you are using WordPress’ dashboard, it will have some items on the list that happen only then and not when someone visits your site.

This is very useful, as you can tell WordPress at which point you want your code to be used on its list. It can also be confusing, as two pieces of code that can be executed together will be on different files, and two pieces of code next to each other on the same file can be in different positions on the list.

Because of this, when you add a new function to your site, you can:

  • put it on your theme’s functions.php
  • if it will be executed when using the template, you can put it directly on the template file
  • use a plugin to add your code
  • create your own plugin
  • modify some of WordPress’ core files to add it
    And all of them can work.

It’s important to know WordPress’ Best Practices to make good choices and create our code to not only work but also be maintainable.

  • putting your code in a plugin is better than doing it in your theme, but both are correct
  • having your code in a template file is not the best way to do it, but it only will make it harder to find
  • modifying WordPress’ core files is not only wrong but a security issue, as it will prevent you from updating your WordPress — or you will lose these changes when you do it