What are The Best Ways to Add Code Snippets in WordPress

First thing you must do on every WordPress website is install a WordPress backup plugin. This keeps your WordPress site safe, and you can always restore it from backup in case anything goes wrong.

Sometimes you may find instructions to add code snippets in WordPress theme templates like index.php, single.php, header.php, and more. These code snippets are useful only in those particular templates, so you will have to add them directly to your theme files or create a child theme.

However, most custom code snippets are added into your WordPress theme’s functions.php file. While the tutorial may recommend you to add it in the theme’s functions.php file, there is a much better alternative that works the same way as a functions file.

Let’s take a look at some of the ways you can add custom code snippets in WordPress.

1. Use The Code Snippets WordPress Plugin

This is the safest and most recommended method for beginners. Code Snippets is a WordPress plugin which allows you to easily add and manage custom code snippets on your website.

It comes with a fail-safe switch which immediately deactivates a code snippet if it causes an error. This protects you from losing access to your website when adding a custom code snippet.

Note: Code snippets method is useful for snippets that need to be added in a functions file. If you are asked to add a code snippet in other theme files, then this method will not work.

2. Create a Child Theme to Save Custom Code

The second approach is to create a child theme. Using child theme will keep your changes intact when you update your theme. It will also allow you to add code to other theme files if needed without worrying about updates undoing your changes.

Note: This method will also work for code snippets that are needed to be added in other theme templates.

3. Use a Site-Specific Plugin for Custom Code

Another flexible option is to use a site-specific WordPress plugin. This is a custom plugin that you can create for your own website and use it to save all your custom code.

The advantage of this method is that your code is not dependent on your theme, and it will remain active even when you change themes. It is also not affected by any WordPress updates on your website.

Note: This method is only applicable for code snippets that need to be added in functions file.

4. Add Code Directly To Functions File

It is OK to add code snippets in your theme’s functions.php file. However, there are some downsides to it.

  • Your changes will be wiped off when you update your WordPress theme
  • Your code will only work if you are using that particular theme

That being said, let’s take a look at how to properly copy and paste code snippets and avoid breaking your website.