At WPBeginner, we often publish tutorials asking users to add code snippets into WordPress. Copying and pasting code in WordPress theme files may seem easy to experienced users, but it is quite tedious and intimidating for beginners. Due to unfamiliarity with coding, beginners may end up making a mistake that could crash their website. In this step by step guide, we will show you how to copy and paste code snippets from web into WordPress.
Why Add Code Snippets to Your WordPress Site?
WordPress is the best website builder in the world due to the flexibility it offers. It is super easy to add new features and functionality to your WordPress website.
WordPress resource sites, like WPBeginner share tips and hacks that you can add to improve your website. While adding custom code snippets to your website is optional, and you can often find plugins to do the same task, sometimes a simple snippet is more efficient.
Some code snippets can be very handy and can help you fix many common WordPress errors, improve WordPress security, and even add new features to your website.
That being said, let’s take a look at how to safely add code snippets into your WordPress website.
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.
For detailed instructions, see our guide on how to easily add custom code snippets in WordPress.
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.
For more details, see our guide on how to create a child theme in WordPress.
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.
See our guide on how to make a site-specific plugin for your website for detailed instructions.
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.
How to Edit WordPress Files?
There are different ways to edit WordPress files depending on which method you choose to add custom code snippets on your website.
1. Adding Custom Code in Code Snippets Plugin
If you are using the Code Snippets plugin, then you can easily add code snippets from WordPress admin area. Simply go to Snippets » Add New page to add your custom code.
2. Adding Custom Code in Site-Specific WordPress Plugin
If you are adding custom code in a site-specific plugin, then you can use the built-in WordPress plugin editor to add custom code.
First, select your site-specific plugin from the drop down menu labeled ‘Select plugin to edit’. The editor will load your plugin file, and you will be able to add code snippets in it.
Once you are done, click on the ‘Update File’ button to save your changes.
If there is something missing in your code or it has potential to break your website, then the plugin editor will automatically undo your changes.
Another method to add custom code in a site-specific plugin is by using FTP.
Simply go to the plugin folder using your FTP client. Right click on the plugin file and then select View/Edit file.
3. Adding Custom Code to functions.php or Other Theme Templates
If you are adding code snippets to your theme’s functions.php file or any other template, then you can add code directly by visiting Appearance » Editor. You can select the file where you need to add the code from the right column.
The instructions you are following will tell you where to paste the code, but if they don’t, then you need to add the code at the bottom of the file.
A better alternative way would be to use FTP to add custom code in theme files. Simply connect your FTP client to your website and go to /wp-content/themes/your-theme-folder/ and right click on the file that needs editing.
Select View/Edit file option to open the file in the text editor.
Troubleshooting PHP Errors when Adding Custom Code
There are some common mistakes that beginners make when adding custom code snippets to their websites. Let’s take a look at some of them and how to avoid them
1. Incorrect Usage of PHP Begin and End Tags
WordPress is written mainly in the PHP programming language which has a specific syntax that tells your server that the following code needs to be processed by PHP. Here is how a typical PHP code snippet looks like:
// PHP Begin Tag <?php // Rest of the code goes here // PHP End Tag ?>
All your PHP code needs to be inside the <?php
and ?>
tags.
The PHP end tag becomes more important in files that switch back and forth in HTML. This includes most WordPress themes files which use PHP tags alongside HTML.
You need to make sure that if you are pasting your code at a location where PHP start tag is not closed then you need to add your code without the starting PHP tag.
<?php // Some pre-existing code // your custom code ?>
If you are pasting your custom code outside or after the PHP end tag, then you need to add the PHP begin tag as well.
<?php // Some pre-existing code ?> // Your custom code snippet <?php ?>
Almost 90% of all errors are caused by incorrect placement of PHP end or start tags. Studying the code will allow you to understand whether or not you need to add the PHP begin or end tags in your custom code snippet.
Many WordPress theme files particularly functions.php file may not have a PHP end tag at all. This means that you can add your code at the bottom of the file without the start or end tags.
<?php // Lots of code in your theme's functions file // // // Your custom code function custom_loginlogo() { echo '<style type="text/css"> h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; } </style>'; } add_action('login_head', 'custom_loginlogo');
Remember that tutorial writers may sometime assume that you already know how to use PHP start and end tags. They may simply show you a code snippet without those tags.
function custom_loginlogo() { echo '<style type="text/css"> h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; } </style>'; } add_action('login_head', 'custom_loginlogo');
Since the tutorial author doesn’t know where you will be adding this code, they have skipped the PHP end and start tags. Now when you are adding such a code snippet in your theme files, you need to make sure that it is inside the PHP tags.
2. Incorrect Nesting Errors
PHP has a particular syntax for functions, conditional logics, and loops. This syntax depends on curly brackets which indicate when a function begins and when it ends.
For example, here is a simple PHP function:
<?php function wpbeginner_tutorial() { echo "Hello World!"; } ?>
Now if you want to add a custom code snippet that has nothing to do with this function, then you will need to put it outside this function like this:
// Pre-existing code in your theme file <?php function wpbeginner_tutorial() { echo "Hello World!"; } // Your custom code function custom_loginlogo() { echo '<style type="text/css"> h1 a {background-image: url('.get_bloginfo('template_directory').'/images/login_logo.png) !important; } </style>'; } ?>
If you miss the starting or ending curly brackets, then this will break the code, and you will end up with an error page.
Understanding PHP Errors in WordPress
Errors caused by adding a custom code in WordPress often result in a detailed error message. Most of them are syntax error, parse errors, or fatal errors due to unexpected characters.
The good part is that these errors will tell you which line in your code caused the error.
You can then go to the exact line to review the code and figure out what you missed. For this purpose we recommend using a proper text editor for code editing because they have line numbers and syntax highlighting which can help you fix the issue easily.
What to do When Your WordPress Site is Inaccessible?
First of all don’t panic. Simply connect to your website using a FTP client or File Manager app in cPanel. Next, locate the file where you added the code that caused the error and edit it.
You can try and fixing the issues with the code snippet. If you are unable to fix those issues, then remove the code and save your changes.
Your site should be back to normal again. If it is still showing some error, then download a fresh copy of your WordPress theme and extract the zip file to your computer.
Upload the file where you made the changes from your computer to your website while overwriting the old file.
For more ways to solve these issues, see our guide on most common WordPress errors and how to fix them. If that doesn’t help then follow our WordPress troubleshooting guide to perform a step by step diagnosis.
We hope this article helped you learn how to paste code snippets from the web into WordPress. Need some code snippets that you can try on your website? See our list of extremely useful tricks for the WordPress functions file.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
why image uploading option was not mention
Thanks for the article but it’s really thrown my understanding of the functions.php file. Is a closing tag really required on every theme’ s Functions file. For example, looking at a clean, untouched installation of the popular Divi theme, there is no closing php tag: ?>
Divi works perfectly without this closing tag so I am assuming that some themes’ Functions.php files don’t require it?
Another point – many people giving out snippets (yourself included) include line numbers as part of the code. When the code snippets are pasted into the functions.php file you then need to go through each line deleting the line numbers, and only the line numbers. If you don’t do this the code breaks and won’t work. I expect this is a very common mistake too. So it would be preferable to avoid these potential problems by posting the code in your tutorials without the line numbers so we don’t have to tediously edit the line numbers out after pasting and risk corrupting the code.
Hey Max,
Good questions. You are right, it is not necessary to add the closing php tag at the end of the functions file.
As for line numbers in code snippets, you will notice a tiny menu when you take your mouse over to a code snippet on WPBeginner. This menu contains a view source or copy button. Clicking on it will open a popup window where you can copy the raw code without line numbers.
Hope this helps.
I read this article and it is really nice. Just to know one thing, what are the sentences written in green in above tutorial? Are they comments or something else? Help me with this.
Hey Mayaprakash,
Yes those are comments to help users understand whats happening in the code.
Thank you my dear for your support. you have saved a brother from loosing he’s job appointment… Thanks and Best regards
A very easy to understand article and explained a great topic.
You’ve done a wonderful job describing a somewhat technical topic in an easy-to-understand, straightforward way. Your examples are simple and really help. Kudos!
Thanks Dylan
Very common mistake also for me. We always have to aware of this.
It is really help full, even i am knowing a little codding. it is really help full and now i know it even better. thanks.
Hey Asanka,
Glad you find it helpful
You may also want to subscribe to our YouTube Channel for WordPress video tutorials.
I’m laughing out loud because it’s as if you’d written the article based on the mistakes I just made! Thank you so much for spelling out the little details as I was quickly back up and running thanks to this article.
Thanks for this easy to follow article!
Whenever i comment and uncomment the codes it creates an error sometimes of “;” or sometimes of “/”.
I again uploaded the file in which there were no changes but still the same error occurs.
Stuck badly.. What to do next.
Help! I just made one of the mistakes mentioned above and my site is broken. I saw your reply to Amy but can’t figure out how to change my function php. Please help!
I have a child theme installed and activated, and I added google analytics code to ‘Appearance> Editor> Theme Functions (functions.php) which was empty and now my site is broken? its a huge issue as there si currently facebook promo running driving people to a broken site.
Syed can you please help me!!
Hi Amy,
You will need access to cPanel dashboard for your web hosting account or FTP credentials. Once you have those, you can connect to your WordPress site using FTP or you can use File Manager from your hosting account dashboard. Locate your theme’s functions.php file and edit it. You will need to go to line 14 to remove the unexpected code or remove the code that you entered earlier causing the issue.
hi i tried to paste a font on php, im newbie on this below is the code can anyone see which is my mistake….
<html >
<link rel="Shortcut Icon" href="/images/favicon.ico ” type=”image/x-icon” />
<link rel="pingback" href="” />
<?php
wp_head();
So using the example above, please could you advise which tags would be stripped from your code snippet below, if you were to paste the code into an existing functions.php file that already had an opening and closing tag?
// Paste your Google Analytics code from Step 4 here
I pasted the code to update the date and time of when a post was updated rather than it displaying the “original” date of the post. I posted right after the Google authorship in my Genesis Child Theme. It’s displaying the updated date but it doesn’t say “Updated. . . “, it just shows the original date and underneath shows the updated date. The file starts with in the file, so my thinking is I have too many “php” in the code. I’m sure it is not placed inside another function. Any help would be greatly appreciated. Here is the code:
add_action(‘genesis_before_post_content’, ‘add_last_modified_date’);
function add_last_modified_date() {
if (is_single()) { ?>
<time datetime="”>
<?php }
}
This is the code BEFORE where I placed the above code:
960, ‘height’ => 80 ) ); ** commented out by payam 09-06-11 to add my own logo and header bg
/** Add support for 3-column footer widgets **/
add_theme_support( ‘genesis-footer-widgets’, 3 );
/* ACF Options page */
if(function_exists(‘acf_add_options_page’)) {
acf_add_options_page( ‘Site Options’ );
// acf_add_options_sub_page(‘Header’);
// acf_add_options_sub_page(‘Footer’);
}
/* payam add google publisher authorship info to home page only */
add_action(‘genesis_meta’, ‘child_google_publisher_authorship’);
function child_google_publisher_authorship() {
if ( is_front_page() ) {
$ED_google_publisher_authorship_link = ” ;
}
echo $ED_google_publisher_authorship_link;
}
Thanks so much!! Saved me from pulling my hair out!
Haha noob friendly article nice
Am I the only one wondering if my google analitics information can be pasted into my WordPress.com site??? In the past I’ve come across things suggested to be added to WordPress only to find out it does not work for my .com. So tell me. Did I go through all of the analitics set up for nothing? I hope not. Where could you paste the information in WordPress.com? There no place to be found.
Barbara, this guide is for self hosted WordPress.org sites. As for WordPress.com blogs, you can not add Google Analytics code or try to pass any unauthorized code into a free WordPress.com blog. Please see our guide on WordPress.com vs WordPress.org
I was informed that I have to add script to the beggining of: /google_analytics_auto.js’/script/head> in order to change this from relative url to absolute url. This will fix many broken links since I recently changed the IDX to my site. After reading the above instructions, it sounds like I need to use a FTP client like Filezilla to perform this. Is this correct?
Hello,
I found your tutorial unfortunately after I broke my site. I am getting this error:
Parse error: syntax error, unexpected T_IF in /home/content/45/7334345/html/wp-content/themes/Magazine110613/functions.php on line 31
But I cannot access the admin panel to fix the code. Any suggestions?
Thanks!
You can fix this by accessing your site using an FTP client like Filezilla. Download a fresh copy of your theme and extract it on your computer, then you need to upload the new functions.php file from your computer to to your theme directory using the FTP client.
Hi I was referred to your article from this link:
http://cyberchimps.com/guide/make-responsive-unresponsive/
I have a question, since I have my child theme installed and activated, is adding the PHP code as simple as going to ‘Appearance> Editor> Theme Functions (functions.php) [which is empty]’ and pasting it?
Or are there other files that need to be edited?
Thanks, hope you can help.
It is that simple, but you have to be very careful with the proper syntax that we have highlighted in the article above. If you paste the code incorrectly, then you can potentially lock yourself out of your WordPress admin. This is why we highly recommend that you know how to use FTP before modifying code through WordPress admin.
Wow, this is the 1st ever article I have seen on the web which acknowledges the fact that newbies who want to get things done with adding code do not necessarily know the assumptions that tutorial writers often have.
This is a very thoughtful and great gesture on your part. Thank You.
I do not blame the experts since they are writing form another level, but seriously, it wouldn’t hurt them or take any extra time to just add the 1 or 2 lines to make sure their code is understood by everyone.
Right now I am looking around for the explanation of another basic thing that must be obvious to all the PHP pros but is totally lost on me, which is, what do they mean when they say “Paste the code below within the single.php within the loop” . . .
What’s “within the loop” here and where should I paste the code snippet in my single.php file ?
Any ideas please ?
Sean, in WordPress terminology, the loop refers to the WordPress Loop. It is the code that runs a loop, generating HTML for posts fetched by the SQL query run by WordPress. It starts like this:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
and ends like this:
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
When you are asked to paste a snippet inside the loop you need to paste it between the start and end of the loop.
Nice, thoughtful article. There are many little things a beginner must know, like these simple errors, that are quickly taken for granted once we learn them. It’s these little things that often cause people to just give up. But that keeps some of us in business :-).
Thanks for this – the one questions that I have is that often I have seen that there are ‘code snippets’ that are offered, but I have NO idea which file they are to be pasted into!
Others, like the one that talks about Displaying Custom Fields here:
http://codex.wordpress.org/Using_Custom_Fields#Displaying_Custom_Fields
The links to “The Loop” quickly get very unclear when they make statements like:
The Loop should be placed in index.php
and
……..in any other Templates used to display post information.<=== they must be kidding, right?
This is where I get very frustrated. How am I supposed to know what "Any of the OTHER Templates used to display post information" is supposed to mean.
Any guidance you could give on this would be greatly appreciated.
Hey Greg,
It is definitely a tough question as to where to paste the code because the answer varies based on the situation. If it is a theme based function, then you would use functions.php file (or another theme file). If it is a site based function, then you probably want to use a site-specific plugin.
The Loop is used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page, and formats it according to how it matches specified criteria within The Loop tags. Any HTML or PHP code contained in the Loop will be processed on each post. You read more about it here: http://codex.wordpress.org/The_Loop
As for template files, you can get a better overview here: http://codex.wordpress.org/Template_Hierarchy#Visual_Overview
Not all themes have all these template files. The most basic theme only needs style.css file and an index.php file. But the more customization you want, the more options you have available for you. The visual overview in the link above should explain that.
“The loop should be placed in index.php” is the very bare bone example. Some themes have separate loop files altogether (i.e loop.php or loop-content.php, loop-quote.php etc). Then the theme author would call those loop files into other template files like single.php where they can say get_template_part( ‘loop’, ‘single’ ); which will include the loop-single.php file. Theme authors have different practices to make things work. It also depends on whether you are using a parent theme or a child theme. Because in child themes, you are mainly just working with the functions.php file and hooks available in the theme framework. Yes it gets pretty tricky when it comes to the child themes.
In your very first example:
//This is the opening tag of a PHP Code
<?php
the comment *before* the opening tag of a PHP Code won't run very well
Not a big deal as few people will paste that anywhere but as the whole guide is about learning how to mix PHP code correctly with HTML and other PHP code …
Just using that for explanation purposes.
I used to make these mistakes and there was never an article like this to help me learn. Thanks for writing this up for newbies!