Custom (PHP) snippets in WordPress

Often you will see tutorials that describe how to customize WordPress and, frequently, they will suggest you do this by adding snippets of code. How best to do this? Personally, I like to add mine to files within the mu-plugin (must-use plugins) directory. PHP files in this location will always be loaded by WordPress, on every single request:

- wp-content
    - mu-plugins  ← Add custom snippets here!
    - plugins
    - themes
    - uploads

The mu-plugin directory does not exist by default, so you may need to manually create it first. Then, structure things however you like. I tend to always have at least one local.php file that contains a wide range of simple snippets and sometimes a few other more specific files. For instance, in addition to various general purpose snippets in my local.php file, I might place all my WooCommerce-related snippets in woocommerce.php, and so on:

- wp-content
    - mu-plugins
        - local.php
        - woocommerce.php

Note that only the top-level files from this directory will be automatically loaded, so if you have lots of snippets and want to organize them in a series of sub-directories, you will need to figure out your own way of loading them.

What about a snippet manager?

There are lots of other ways of adding snippets, such as by using plugins like Code Snippets (which I've also used successfully on many occasions—however there are lots of other options out there, too) that may even be better. Whether this is the right choice depends on the project, your level of comfort, level of access, and possibly also whether or not you are working as part of a team. 

A nice feature of many snippet manager plugins is that they let you go beyond "mere PHP-based snippets" by making it trivial to also insert custom CSS, JS, and more. Some (including the aforementioned Code Snippets) also have added safety features, to help guard against various types of error.

You may also like:

Can I replace a (PHP) built-in?

How fast is PHP's str_starts_with() function? Let's pretend it's excruciatingly slow (it isn't) and that we believe we can replace...