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.
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.
- 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