If you’ve thought about modifying your WooCommerce store then you’ve probably come across code snippets online, code snippets can be useful and provide the ability to add extra functionality to your store with a simple copy and paste, but how should you add a snippet to your store?
What’s the best way to add a Code Snippet to WooCommerce?
In this article, we’ll look at four different ways to add code snippets to your store. here are the four methods we’ll look at
- using the functions.php file in your theme
- using the functions.php file in your child theme
- using a code snippets plugin
- writing a plugin
For each method, we’ll detail how it’s done and then look at its pros and cons.
Using the functions.php File in Your Theme
This may well be the most tempting way to add a snippet, it’s potentially very quick, but it’s also probably the most unsafe method both in terms of keeping the functionally you add and also in terms of breaking your site.
How it’s Done
There are two ways to make a change via this method
FTP
This is the safest way to make a change using this method, here’s how to do it.
Use an FTP client such as FileZilla to connect to your website, to do this you’ll need an FTP URL, username, and password, these should all be available from your hosting company.
Once you have accessed your site via FTP use your FTP client to access the “wp-content\themes\” folder within your website. From here choose the folder that corresponds to the theme name you are currently running on your site.
In the screenshot above you can see how I’ve accessed the “storefront” theme folder and found the functions.php file. To add a snippet to your site you should just need to append it to the end of the “functions.php” file. Once you have located the file then you can either edit it via the FTP client or download it to your machine, edit it (we’d strongly recommend backing the file up first) and then upload the changed file back to your server.
Via the WordPress Admin Dashboard
Before explaining this method, we really should point out that we strongly advise against using it. It is quick, but it can also lead to your site being taken offline.
We considered not including this method in the article at all because it’s so dangerous but thought it was better to explain it rather than just ignoring it.
To make the change via the dashboard go to “Appearance -> Editor”, this should open the editor, and you should see a theme files menu on the right-hand side of the screen. From here choose the “functions.php” file
The menu may look different to the above depending on what theme you are using.
The “functions.php” file should now open in the editor and you can add your snippet before saving the file.
The real danger of this method is that if you copy in some bad code or make an error when adding your code, then it could lead to your site becoming unavailable, the most common way this manifests itself is when you visit your site all you can see is a blank white screen.
Unfortunately, the admin area of your site also becomes unavailable, so unless you have FTP access to your site then it will be incredibly difficult to get your site up and running again.
The main advantage of the FTP Method over this one is that if you add some bad code using the FTP method you can just edit te file again and remove the offending code, using this method if you make any mistakes then you may no longer be able to access the file editor.
Will the Editor Allow Me to Enter Bad Code?
In later versions of WordPress the editor checks code before saving, so this should catch a number of cases where bad code is entered, but it would be wrong to rely on this check.
The editor is able to check if code entered can be compiled, but it is possible to add compilable code that would introduce problems that could bring down your site, such as infinite loops.
So while there are some safeguards in place we would always advise the utmost caution when using this method.
This is an extract from the book “Learning WooCommerce Development By Example”, click here to find out more.
Pros and Cons of Adding Snippets to the functions.php File in Your Theme
Pro
The only real pro to this method is that it’s quick.
Cons
As mentioned previously you could make your entire site unavailable using this method, whilst making the change via FTP lessens the risk of this it still makes it a risky option.
The other major drawback of this method is that when themes get updated the “functions.php” file can be overwritten, this could lead to you losing all the functionality that you have added via the “functions.php” file when you update your theme.
Using the functions.php File in Your Child Theme
This method is a very similar method to the one above, the only difference is that you’ll make changes to the “functions.php” file in a child theme rather than directly to a theme.
Just like the theme “functions.php” method, you can do this via FTP or via the admin interface (the admin interface will give you access to the “functions.php” file in your child theme).
This method also presents the same dangers as the previous method, and if you add bad code to your child theme “functions.php” you could still make your store inaccessible.
Pros and Cons of Adding Snippets to the functions.php File in Your Child Theme
Pros
This is the real difference to using this method, if you add the snippet to your child theme then you won’t lose any added functionality when the child theme’s parent updates. In theory, the “functions.php” file should never be overwritten by updates to your site/themes.
Cons
These are pretty much identical to the cons of the previous method.
One other thing to point out is that adding snippets to your themes via the”functions.php” file will mean you will lose all of the functionality you’ve added if you ever change your theme. The next couple of methods that we are going to look at will get around this problem.
Via a Third Party Plugin
You can avoid updating a “functions.php” completely by adding code snippets via a plug-in, in this article, we’ll take a look at how to do this via the Code Snippets plugin.
Once you have installed the plugin then a number of options are added to the WordPress admin area
If you choose “Add New” then you will be presented with an editor to add a new snippet
As you can see from the screenshot above you are prompted if you are entering bad code, the code editor also has an autocomplete function (which can be turned off in the plug-in settings) so it will try to complete any brackets or braces that you add to your code.
If you still go ahead and try and save some code that the plug-in considers dangerous then it will refuse to save the snippet and show a message similar to the one below
The plugin also allows snippets to be specifically targetted at the front or back end of your site, so even if you add a snippet that wrecks your customer-facing pages you should still be able to fix it in the back end.
If all else fails and you’ve added a snippet that both breaks your site and you’re unable to get access to your admin area to fix it, then the plugin provides a method where you can disable all added snippets by adding a line of text to a WordPress settings file. You will need FTP access to your site to do this though.
Another advantage of using the plugin is that snippets can be turned on and off, so it’s easy to remove snippets without having to delete them from/comment them out in the “functions.php” file.
Snippets can also be categorized using tags, so if you’re running a lot of snippets on your store you can easily sort them into areas of functionality pages they run on, and then turn them on and off accordingly. It is also possible to add titles and descriptions for each snippet. Being able to categorize and describe snippets in this way makes it much easier to keep track of your snippets, and is certainly preferable to scrolling through a text file trying to work out what each added snippet does.
The plugin also has the functionality to add CSS and Javascript snippets your store which is something that would be much more difficult to do via the “functions.php” file unless you had some coding knowledge. The plugin provides examples of how to add Javascript and CSS so you should be able to copy these and add the required styles or scripts to your store.
Pros and Cons of Adding Snippets via a Third Party Plugin
Pros
You don’t need to chnage any code files.
It’s much easier to categorize and organize your snippets.
You can add CSS and Javascript snippets reasonably easily.
Any snippets you add are not linked to your theme, so even if you swap themes any snippets added via the plugin will still remain intact.
Cons
Although the plugin makes it hard to add bad code, it is still possible to break your site by adding a snippet containing bad code. The plugin provides a workaround for this but you’ll need FTP access to your site in order to implement it.
If you’re doing client work then some clients may object to code been added via a plugin, we will take a look at how to create our own plugins in the next method.
Via a Plugin we Write Ourselves
WordPress makes it reasonably easy to create a plugin and we can use this functionality to add snippets to our site, let’s take a look at how we would do this.
Firstly, we will create a folder for a plugin in the “public\wp-content\plugins\” directory of our WordPress site, the image below shows me creating a directory using FileZilla
Once we have created the directory then we we will create a php file with the same name (hwn-snippets-plugin.php), we will then add the following code to the file.
<?php /** * Plugin Name: Hard Working Nerd Snippets Plugin * Description: An example to show how to add snippets via a plugin * Author: Ian Preston * Version: 1.0 */ /* Put your snippets below here. */ /* Put your snippets above here. */ ?>
As you can see from the code above we have not yet added any functional code, but we have provided the information that WordPress requires to register a plugin. We can confirm this by looking at the plugins page in the WordPress dashboard, where we should see our new plugin has been added.
Now we can see our plugin, let’s add some code
add_filter( 'woocommerce_loop_add_to_cart_link', 'hwn_replace_add_to_cart_button', 10, 2 ); function hwn_replace_add_to_cart_button( $button, $product ) { $button_text = __("View Product", "woocommerce"); $button = '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>'; return $button; }
The code above removes the “Add to Cart” button on the shop page and replaces it with a “View Product” button that takes the user to the product detail page (you can find more information about this code here). If we add the code above to the plugin file between the comments telling us where to insert our code and then activate the plugin then we should see the following on our shop page.
Now if we want to turn off our functionality then we can deactivate our plugin and the original functionality is restored
One of the drawbacks to adding snippet functionality via a plugin is that a user could inadvertently de-activate our plugin and then all of the associated functionality would disappear from the site, we can get around this by converting our plugin to a “must use” plugin.
Here’s how.
Firstly we’ll create a new folder in “\wp-content\” named “mu-plugins”.
Now if we move the “hwn-snippets-plugin.php” file from “\wp-content\plugins\hwn-snippets-plugin\” to “\wp-content\mu-plugins” and refresh the plugins section in the WP dashboard, we should now see a new “Must-Use” menu item.
Our plugin should now be displayed under this section
Now the plugin has bee converted to a must-use plugin any functionality included in the plugin will be turned on by default, and the plugin will only be de-activated if it is removed from the “mu-plugins” directory.
Pros and Cons of Adding Snippets via a Plugin We Write Ourselves
Pros
Any added functionality is not linked to the store’s theme, so any snippets added will carry on working if the theme is switched.
Potentially looks more professional than using a third party plugin if you are working for a client.
Snippets can be split into different plugins and then activated/de-activated as required.
Cons
Unless a must-use plugin is used it is possible to disable functionality by de-activating the plugin.
Not as easy to categorize and sort snippets as when using a third-party plugin.
Final Thoughts and Looking Ahead to Tomorrows Lesson
There are a number of different ways to add snippets to your WooCommerce store, each has its pros and cons and it is a matter of personal choice which one you decide to use.
Having said that, there are a number of risks in adding snippets to your “functions.php” file so unless you have good reasons for doing this we would recommend you go with one of the plugin options.
In tomorrow’s lesson we’ll take a look at actions which are one of the main building blocks for WooCommerce development and are often used in WooCommerce code snippets, looking forward to seeing you again then 🙂