How to Manage and Use Code Snippets in WordPress
In previous posts, we have gone through some WordPress customization that involve code addition in
functions.php. These additions enhance the functionality of our theme.
Take our WordPress Login Page tutorial for example, we are able to redirect users from the default WordPress login page,
wp-login.php, to our new customized login page, and also redirect them to another page upon logout.
However, after a while, the list of codes that we’ve added in the
functions.php could pile up and get very messy. If you are experiencing this problem, we’ve got some tips here to help you tackle this.
Recommended Reading: Beginner’s Guide To WordPress Plugin Development
Creating Multiple Files
The first thing we can do to manage our codes is by separating a set of codes into different files. Say, we have a couple of new functions that alter the Login Page. We could store these codes in a new file rather than putting it in the
Create a new file,
custom-login.php (as an example), and put all the codes in it. Then, in function.php, refer to this file with
require_once, like so.
require_once get_template_directory() . '/inc/custom-login.php';
And that’s it. Note that this method requires you to be careful when separating the codes, otherwise you could break the site. You should also be very clear in naming the files, so that people who work on your theme – particularly, if you are working in a team – can quickly figure out the relationship between each file.
However, if you are not that familiar with PHP or are afraid of ruining the site when altering the files, try the next tip instead.
Code Snippet Plugin
Code Snippets is a plugin created by Shea Bunge. It provides a native WordPress GUI to add your code snippets, and run them on your site. In other words, instead of adding the code in
functions.php, you can do it through the WordPress back-end administration.
Once it is installed and activated, you will find a new side-menu below the Plugins.
You can create a new code snippet, just as you would create a new post and page.
Click on the Activate button to use the code in your site. So with this, we not only store the codes but can activate them to function within the site.
You can also hit the Export button to download the code in a PHP file.
One of the advantages of using Code Snippets is that instead of having to input all the codes in the
functions.php of the theme once again, the functionality of the codes will still be able to run, even if we have changed the theme.
Alright, those are the two tips that we’ve got. It is now up to you to decide on which one best fits your requirements. We hope you find these tips useful. If you know of any other methods, let us know in the comments.