How to Easily Add Custom Code in WordPress (Without Breaking Your Site)

Often while reading WordPress tutorials, you may be asked to add custom code snippets in your theme’s functions.php file or in a site-specific plugin.

The problem is that even the slightest mistake can break your website.

In this article, we will show you an easy way to add custom code in WordPress without breaking your site.

How to easily add custom code in WordPress

The Problem with Custom Code Snippets (And How to Fix It)

Often you’ll find code snippets in WordPress tutorials with instructions to add them into your theme’s functions.php file or a site-specific plugin.

The biggest problem is that even a tiny mistake in the custom code snippet can break your WordPress site and make it inaccessible.

Not to mention, if you update your WordPress theme, then all your customizations get removed.

The other problem is that if you add multiple code snippets in a site-specific plugin, it can become hard to manage the file.

Luckily, there is an easier way for users to add and manage custom code snippets in WordPress.

WPCode is the most popular code snippets plugin used by over 1 million WordPress websites. It makes it easy to add code snippets in WordPress without having to edit your theme’s functions.php file.

WPCode Code Snippets Plugin

WPCode also makes it simple to add tracking codes for Google Analytics, Facebook Pixel, Google AdSense, and more to your site’s header and footer areas.

You’ll never have to worry about breaking your site because the smart code snippet validation helps you prevent common code errors.

In addition, WPCode comes with a built-in snippets library where you can find all of the most popular WordPress code snippets like disable REST API, disable comments, disable Gutenberg, allow SVG file uploads, and much more. This eliminates the need to install separate plugins for each feature request.

The best part is that you can manage all your code snippets from one central screen and add tags to organize them.

With that said, let’s take a look at how to easily add custom code snippets in WordPress with WPCode.

Adding Custom Code Snippets in WordPress

The first thing you need to do is install and activate the WPCode plugin on your website.

For more details, see our step by step guide on how to install a WordPress plugin.

Upon activation, the plugin will add a new menu item labeled ‘Code Snippets’ to your WordPress admin bar. Clicking on it will show you a list of all the custom code snippets you have saved on your site.

Since you just installed the plugin, your list will be empty.

Go ahead and click on the ‘Add New’ button to add your first custom code snippet in WordPress.

Click 'Add New' in WPCode to create a new custom snippet

This will bring you to the ‘Add Snippet’ page. Here you can choose a code snippet from the pre-made library or add your custom code.

To add custom code, click on the ‘Use snippet’ button underneath the ‘Add Your Custom Code (New Snippet)’ option.

Add custom code in WPCode

You need to start by entering a title for your custom code snippet. This could be anything that helps you identify the code.

After that, you can copy and paste your code snippet into the code box. Be sure to also select the correct code type from the drop-down menu on the right.

Adding your first code snippet

In the screenshot above, we have added a custom code snippet to remove the WordPress version number from our test site.

function wpb_remove_version() {
return '';
}
add_filter('the_generator', 'wpb_remove_version');

Below the code box, you will see insertion options. There are two main insertion options: Auto Insert and Shortcode (Default).

Choose insertion option for code snippet

If you chose the ‘Auto Insert’ method, the snippet will be automatically inserted and executed on your site.

You can automatically run the snippet only in the WordPress admin area, on the front-end of your site, or everywhere. If you are unsure, then select the default ‘Run snippet everywhere’ option.

With the ‘Shortcode’ method, the snippet is not automatically inserted. Once you save the snippet, you’ll get a shortcode specific to the snippet that you can use anywhere on your site.

When you scroll further down, you will see a ‘Basic info’ area. You can add anything here that helps you understand what this code does, where you found it, and why you are adding it to your website.

Add code description and tags

You can also assign tags to your code snippet. This will help you sort your code snippets by topic and functionality.

The priority field allows you to control the order in which the snippets are executed when you want to display multiple snippets in the same location. By default, all snippets get a priority of 10. If you want a snippet to display earlier than others, simply set the snippet priority to a lower number, like 5.

Lastly, you can use the powerful ‘Smart Conditional Logic’ section to either show or hide auto-inserted snippets based on a set of rules.

Use smart conditional logic to show or hide snippets

For example, you can show code snippets to logged-in users only, load code snippets only on specific page URLs, and more.

When you’re finished choosing options, you can click the ‘Save Snippet’ button in the top-right corner of the screen and toggle the switch from ‘Inactive’ to ‘Active.’

Save and activate code snippet

If you want to save the code snippet and not activate it, then simply click on the ‘Save Snippet’ button.

Once you have saved and activated the code snippet, it will be added to your site automatically, if that’s the insertion method you chose, or displayed as a shortcode.

Handling Errors in Custom Code

Often, if you make a mistake in adding the custom code in your site-specific plugin or theme file, then it would immediately make your site inaccessible.

You would start seeing a syntax error or a 500 internal server error on your site. To fix this you’ll need to manually undo your code using an FTP client.

The neat part about the WPCode plugin is that it will automatically detect a syntax error in the code and immediately deactivate it.

Error handling in your custom code snippet

It will also show you a helpful error message, so you can debug the error.

WPCode’s smart code snippet validation will also detect any errors as you’re adding your custom code.

Smart code snippet validation to find code errors

Hovering over the error will bring up instructions to help you fix it.

Managing Your Custom Code Snippets

WPCode plugin provides an easy user interface to manage your custom code snippets in WordPress.

You can save code snippets without activating them on your site, and then activate or deactivate the snippet at any time you want. It’s also possible to filter code snippets by type and location, and use tags to organize your code snippets easily.

WPCode - WordPress Snippets Organized by Tags

You can also export specific code snippets or bulk export all of them.

Simply go to Code Snippets » Tools and click on the ‘Export’ tab.

Export your custom code snippets

If you’re moving websites to a different server, you can easily import your code snippets to the new site.

Just visit the Code Snippets » Tools » Import page and upload the export file.

Import code snippets with WPCode

We hope this article helped you learn how to easily add custom code in WordPress. Want to experiment with some code snippets on your website? Check out our list of extremely useful tricks for the WordPress functions file, and don’t forget to see our ultimate guide to speeding up your WordPress site.

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.

The post How to Easily Add Custom Code in WordPress (Without Breaking Your Site) first appeared on WPBeginner.

How to Properly Install and Setup WP Rocket in WordPress

Do you want to properly install and setup WP Rocket plugin in WordPress?

WP Rocket is the best WordPress caching plugin in the market because it offers the most comprehensive set of tools to help speed up your website.

However, many beginners are not familiar with the techy lingo and may find it difficult to decide which plugin options they should turn on.

In this tutorial, we will show you how to easily install and setup WP Rocket plugin in WordPress. We will walk you through complete WP Rocket plugin settings, so you can get maximum performance benefits.

How to easily install and setup WP Rocket plugin in WordPress

Why Use WP Rocket?

No one likes slow websites. In fact, a performance study found that a single second delay in page load time costs 7% less conversions, 11% fewer page views, and 16% decrease in customer satisfaction.

Strangeloop Study

And it’s not just users, search engines like Google also don’t like slow websites. They give a priority to faster websites in search rankings.

This is where WP Rocket comes in.

It is the best WordPress caching plugin on the market and allows you to quickly improve your WordPress website’s speed and performance.

Here is how it works.

WordPress is a dynamic content management system. Every time a user visits your website, WordPress fetches the content from your database, generate a page on the fly, and send it back to the user.

WordPress caching

This process takes up WordPress hosting server resources. If a lot of people visit your website at once, then this would slow down your website.

WP Rocket makes WordPress bypass all this.

It crawls and saves a static copy of your pages in the cache and allows WordPress to show the cached page to the user instead of generating a page on the fly.

This frees up server resources on your website and improves overall page load time throughout your website.

We use WP Rocket on many of our own websites including WPForms, OptinMonster, etc.

That being said, let’s take a look at how to easily install and set up WP Rocket on your WordPress website.

Step 1. Installing WP Rocket Plugin in WordPress

The first thing you need to do is install and activate the WP Rocket plugin. For more details, see our step by step guide on how to install a WordPress plugin.

WP Rocket is a premium plugin, but the best part is that all features are included in their lowest plan.

Once installed and activated, the WP Rocket plugin works out of the box, and it will turn on caching with optimal settings for your website.

We ran speed tests on our demo site before and after installing WP Rocket. The performance improvement was incredible with just out of the box settings.

Speed test results before and after installing WP Rocket

The performance improvement is instantly noticeable because WP Rocket doesn’t wait for user requests to start caching pages. It proactively crawls your website and preloads pages in the cache.

You can see caching status by visiting WP Rocket dashboard located under Settings » WP Rocket page.

WP Rocket dashboard

Now that you have installed WP Rocket, let’s take a look at other WP Rocket options and how to set them up to further improve your website speed.

Step 2. Set up Caching Options in WP Rocket

Fist, you need to visit Settings » WP Rocket page and click on the ‘Cache’ tab.

Setting up cache in WP Rocket

WP Rocket has already enabled page caching by default, but you can tweak the settings to further improve your website speed.

1. Mobile Caching

You’ll notice that mobile caching is turned on by default here. However, we recommend you to check the ‘Separate cache files for mobile devices’ option as well.

This option allows WP Rocket to create separate cache files for mobile users. Checking this option ensures that mobile users get the full cached mobile experience.

2. User Cache

If you run a website where users need to login to your website to access certain features, then you need to check this option.

For example, if you run a WooCommerce store or a membership website, then this option will improve user experience for all logged in users.

3. Cache Lifespan

Cache lifespan is the time you want to store the cached files on your website. The default limit is set to 10 hours which would work for most websites.

However, you can set it to a lower value if you run a very busy site. You can also set it to a higher value if you don’t update your website frequently.

After the lifespan time has passed, WP Rocket will delete the cached files. It will also immediately start preloading the cache with updated content.

Don’t forget to click on the Save Changes button to store your settings.

Step 3. Minifying Files using WP Rocket

WP Rocket enables you to minify static files such as JavaScript and CSS stylesheets. You can simply switch to the File Optimization tab and check the boxes for the file types that you want to be minified.

Minifying files in WP Rocket

Minifying static content makes those file sizes smaller. In most cases, this difference is too small to make any noticeable impact on your website’s performance.

However if you run a large traffic site, then this can definitely have a big impact in reducing your overall bandwidth usage and saving on hosting costs.

The one caveat is that minifying files can also have unexpected consequences like files not loading or not working as intended.

If you turn this setting on, then please make sure to thoroughly review your website pages to make sure everything is working as intended.

Step 4. Lazy Load Media to Improve Page Load Speed

Images are often the second heaviest item on a page after video. Images take more time to load than text and increase the overall page download size.

Most popular websites now use a technique called lazy loading to delay image downloads.

Instead of loading all your images at once, lazy loading downloads only the images that will be visible on the user’s screen. This not only makes your pages load fast, but it also feels faster to the user.

WP Rocket comes with a built-in lazy loading feature. You can enable lady loading for images by simply switching to the Media tab on the plugin’s settings page. You can also enable lazy loading for embeds like YouTube videos and iframes.

Lazy load images and embeds in WordPress

Note: While lazy loading images will help improve perceived website speed, you should always save and optimize images for web to get maximum results. Here’s how to easily optimize images for web performance (step by step).

Step 5. Fine Tune Preloading in WP Rocket

Next, you can review the preloading settings in WP Rocket by switching to the ‘Preloading’ tab. By default, the plugin starts crawling your homepage and follow links to preload cache.

Preload cache settings

Alternately, you can tell the plugin to use your XML sitemap to build cache.

You can turn off the preloading feature as well, but we do not recommend that.

Turning off preloading will tell WordPress to only cache pages when they are requested by a user. This means the first user to load that specific page will always see a slow website.

Editors note: Please keep preloading on to get maximum performance results.

Step 6. Set up Advanced Caching Rules

WP Rocket gives you full control over caching. You can switch to the Advanced Rules tab on the settings page to exclude pages that you don’t want to be cached.

Advanced caching rules

You can also exclude cookies, user agents (browsers and device types), and automatically rebuild cache when you update specific pages or posts.

The default settings would work for most websites. If you are unsure about these options, then you need to leave them blank.

This settings area is for developers and power users who need custom settings because they likely have a complex website setup.

Also See: 19 types of websites you can build with WordPress.

Step 7. Performing Database Clean up using WP Rocket

WP Rocket also makes it easy to clean up the WordPress database. It has very little to no effect on your website performance, but you can still review these options if you want to.

You need to switch to the Database tab on the plugin settings page. From here you can delete post revisions, drafts, spam, and trash comments.

Database clean up

We don’t recommend deleting post revisions because they can be really useful in undoing changes to your WordPress posts and pages in the future. You also don’t need to delete spam and trashed comments as WordPress automatically clean them up after 30 days.

Step 8. Configure Your CDN to Work with WP Rocket

Next, you need to switch to the CDN tab. If you are using a CDN service for your WordPress site, then you can set it up to work with WP Rocket.

Set up CDN service

CDN or content delivery network enables you to serve static files from a network of servers spread across the globe.

This speeds up your website because it allows users browser to download files from the server closest to their location. It also reduces your hosting server load and makes your website more responsive.

For more information, see our guide on why you need a CDN service for your WordPress site.

We use MaxCDN by StackPath on our websites. It is one of the best CDN service for WordPress beginners.

Alternately, you can sign up for Sucuri, which is the best WordPress firewall and security plugin. Sucuri’s cloud-based firewall gives you a powerful CDN service to serve your static files.

If you are looking for a free alternative, then Cloudflare would work as well. However, Cloudflare’s free CDN offers limited protection against DDoS attacks, and the free plan is quite limited in terms of features.

WP Rocket has separate addons to easily set up Sucuri and Cloudflare on your website (more on this later).

Step 9. Reducing Heartbeat API Activity in WordPress with WP Rocket

Heartbeat API allows WordPress to send a periodic request to the hosting server in the background. This allows your website to perform scheduled tasks.

For example, when writing blog posts the editor uses heartbeat API to check connectivity and post changes.

Controling heartbeat API in WordPress using WP Rocket

You can click on the Heartbeat API tab to control this feature and reduce the heartbeat API frequency.

We don’t recommend deactivating the Heart Beat API because it offers some very useful features. However you can reduce its frequency to improve performance specially for larger sites.

Step 10. WP Rocket Addons

WP Rocket also comes with some ready to deploy features available as Addons. Let’s take a look at currently available addons on this list.

1. Google Analytics Addon

The Google Analytics add-on for WP Rocket allows you to host Google Analytics code on your own server. This does not have any significant performance improvement but some users want it to get a 100% page speed score.

This feature is compatible with popular Google Analytics plugins like MonsterInsights and ExactMetrics.

2. Facebook Pixel

If you are using the Facebook pixel for user tracking, then this addon will host the pixels locally on your server. Again, this will improve your pagespeed score but may not have any actual impact on website speed.

3. Varnish Addon

If your WordPress hosting company uses Varnish cache, then you need to enable this addon. This will ensure that the Varnish cache is cleared when WP Rocket clears its cache.

4. Cloudflare

If you are using Cloudflare CDN, then you need this addon to make it work alongside WP Rocket. Simply enable the addon and click on the ‘Modify options’ button.

Enabling Cloudflare addon

After that, you need to enter your account credentials to connect WP Rocket with your Cloudflare account.

Cloudflare settings

5. Sucuri

If you are using Sucuri, then you need to enable this addon and click on the ‘Modify options’ button. After that, enter your Sucuri account’s API key to connect your account.

Sucuri WP Rocket addon

Step 11. Managing Your WP Rocket Cache

WP Rocket also makes it easy for admins to manage and clear WordPress cache. Simply go to the plugins settings page, and you’ll find the options to clear WP Rocket cache on the Dashboard tab.

Clear WP Rocket Cache

You can also start a preloading sequence to rebuild the cache on demand.

The plugin also makes it easier to import and export plugin settings. You can switch to the tools to easily export and import plugin settings. This is helpful when moving WordPress from local server to a live website and/or when moving WordPress to a new domain.

Import export settings

Below that, you’ll find the option to Rollback plugin to an earlier version. This comes in handy if a WP Rocket update didn’t work as expected.

If you want to have the same rollback feature for all your plugins, then see our guide on how to rollback plugins to older version in WordPress.

WP Rocket FAQ – Frequently Asked Questions

As WP Rocket has grown in popularity, we have answered many questions related to the WP Rocket WordPress caching plugin. Here are some of the top WP Rocket questions:

1. Is WP Rocket free? Is there a free version of WP Rocket available?

No, WP Rocket is a premium WordPress caching plugin. There is no free version or free trial available. They do offer a 14 day money back guarantee.

You may find a nulled version of WP Rocket for free, but we strongly recommend against using those because sometimes hackers use nulled version as a bait to hack your website.

See 9 reasons why you should always avoid nulled version of WordPress themes and plugins.

2. Is WP Rocket worth the price?

Yes it is worth every penny. We are paying customers of WP Rocket and use it successfully on many of our websites including WPForms, OptinMonster, and others.

We also have plans to switch to WP Rocket on WPBeginner in the near future as well. We are closely working with their team to get one particular setting included for it to work on our complex multi-server enterprise hosting setup.

Curious to see what WPBeginner hosting setup looks like? Check out the detailed case study here.

3. Do I need to use WP Rocket with managed WordPress hosting platforms?

The short answer is yes. You can and should use WP Rocket in combination with built-in caching offered by your managed hosting company to unlock additional performance improvements.

A lot of managed WordPress hosting companies like WP Engine, SiteGround, Bluehost, etc have their own caching plugins built in.

WP Rocket plays nicely along those built-in caching options provided by your managed hosting provider while helping you get additional performance benefits with features like CDN, minifying files, lazy loading, smart cache preloading, and more.

4. How to check if WP Rocket is working and caching pages?

To check if WP Rocket is working properly, you need to log out of your site or open it in an incognito window.

Next, you need to open the browser’s source view of the page, and scroll to the bottom. At the very end, you should see a text like: “This website is like a rocket …”

If that text is there, then you know WP Rocket is working properly and caching pages.

5. What makes WP Rocket better than other caching plugins?

In our opinion, WP Rocket is better than other WordPress caching plugins like W3 Total Cache, WP Super Cache, etc because it offers the most comprehensive set of features, and it is regularly updated to keep up with modern browser standards.

This is the #1 reason why we have started switching all of our sites to use WP Rocket, and soon WPBeginner will be using WP Rocket as well.

We hope this guide helped you learn how to install and set up WP Rocket plugin in WordPress. You may also want to see our ultimate guide on how to speed up WordPress, and our list of the must have WordPress plugins.

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.

The post How to Properly Install and Setup WP Rocket in WordPress appeared first on WPBeginner.

How to Add Header and Footer Code in WordPress (the Easy Way)

Have you ever been asked to add some code snippets to <header> or <footer> section of your WordPress website?

Often you are asked to add header and footer code in WordPress when trying to integrate with web services like Google Analytics, Facebook Pixel, Google Search Console, etc.

You may also come across WordPress tutorials that might ask you to add some custom CSS or Javascript code to your WordPress header or footer.

By default, WordPress doesn’t provide an option to insert code in your website’s header and footer. Luckily there is an easy solution for beginners.

In this article, we will show you how to easily add header and footer code in WordPress. The goal is to safely add the code without directly editing your WordPress theme files.

How to Add Header and Footer Code in WordPress

The Best Way to Add WordPress Header and Footer Code

If you want to add WordPress header and footer code, there are three possible solutions:

  1. Manually, by editing you theme’s header.php and footer.php files
  2. With your theme’s built-in header and footer code feature
  3. Using a plugin

The first option is not beginner friendly because it requires you to add header and footer code by directly editing the header.php and footer.php files manually.

Another disadvantage of using this method is that your code will be removed if you install an update to your theme.

The second option is using your theme’s built-in feature. Some WordPress themes like Elegant Themes and Genesis Framework by StudioPress offer a built-in option for quickly adding code and scripts to your WordPress header and footer.

If you are using a theme with a built-in feature, then it seems like a safe and simple solution. However if you change your theme, then all the code snippets added to your website will be gone. This includes site verification in Google Search Console, website analytics via Google Analytics, etc.

This why we always recommend users to use the third option, a headers and footers plugin. This option is by far the easiest and safest method to add header and footer code in WordPress.

After a lot of request from readers, our team has built a 100% free Insert Headers and Footers plugin to let users easily add code to the header and footer in WordPress.

Insert Headers and Footers

Here are some benefits of using the Insert Headers and Footers plugin:

1. Easy, Fast, and Organized: It lets you add codes to your site’s header and footer easily and quickly. Plus, it keeps you organized by allowing you to store all your footer and header codes in one place.

2. Prevents Errors: It helps prevent errors which may occur if you edit your theme files manually.

3. Upgrade or Change Your Theme Without any Worry: The plugin will save your header and footer code in a separate place, so you can update or change your theme without worrying about the code being erased.

With that said, let’s see how to easily add header and footer code in WordPress using Insert Headers and Footers plugin.

Adding Code to Header and Footer in WordPress

First thing you need to do is install and activate the Insert Headers and Footers plugin. For more details, see our step by step guide on how to install a WordPress plugin.

Once the plugin is activated, go to Settings » Insert Headers and Footers from your admin panel. After that, you will see two boxes for adding code to header and footer.

Insert Headers and Footers plugin settings

Simply paste the code in one of the two boxes. Once done, don’t forget to click the Save button to store your changes.

The plugin will now automatically load the code in the respective locations on your WordPress site.

You can always edit and remove any code that you don’t want to keep.

You’ll need to keep the plugin installed and activated at all times. Deactivating the plugin will stop adding all custom code to your site.

If you accidentally deactivate the plugin, the code will still be safely stored in your WordPress database. You can simply reinstall or reactivate the plugin, and the code will start appearing again.

Note: You may have to clear your WordPress cache after saving changes, so the code properly appears on the front-end of your website.

We have found the biggest reason why a lot of beginners use the Insert Headers and Footers plugin is to add Google Analytics to their website. For that, we actually recommend using the free MonsterInsights plugin. It’s the best Google analytics plugin for WordPress which helps you properly setup Google analytics tracking with just a few clicks, and it shows you helpful stats right inside your WordPress dashboard.

We hope this article helped you to learn how to add header and footer code in WordPress easily. You may also want to see our comparison of the best email marketing services and the best business phone services.

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.

The post How to Add Header and Footer Code in WordPress (the Easy Way) appeared first on WPBeginner.