EDITS.WS

Author: Jen Swisher

  • WordPress REST API: How to Access, Use, & Secure It (Full Tutorial)

    If you’re planning to become a WordPress developer, you’ll come across something called ‘REST API.’ This is an interface that expands the functionality of WordPress and enables you to connect the platform with other applications. Some developers find it really helpful as part of their process — especially if they’re looking to implement advanced functionality. 

    Fortunately, you don’t need to be an experienced developer to gain expertise with the WordPress REST API. Once you have a solid understanding of the interface and how it works, you can easily implement it into your web-building projects.

    In this post, we’ll provide an in-depth guide to the WordPress REST API. We’ll discuss what it is, how to use it, and how to protect it against threats. We’ll also show you how to fix common REST API errors, how to use the interface with other frameworks, and how it compares to other WordPress API solutions.

    What is the WordPress REST API?

    To understand the WordPress REST API, we’ll need to break down its various components. Let’s start with an introduction to APIs.

    What is an API?

    An application programming interface (API) is a program that enables two applications to communicate with one another. It serves as an intermediary between two pieces of software, facilitating a seamless collaboration. 

    For example, if you wanted to display a Google product on your site, like maps, you’d need to use the Google Maps API.

    Google Cloud API library

    This enables your WordPress site to communicate with Google Maps, so it can pull all the relevant data and features needed to display those maps. 

    Like Google, other companies have APIs and provide them to web developers. These products can be very appealing, as they eliminate the need to code a feature (like a map) from scratch. Instead, you can use third-party software and connect it to your site via API.

    What is REST?

    Representational State Transfer (REST) is a set of guidelines that developers must follow when creating APIs. Therefore, a REST API is an interface that was built with these standards in mind.

    Typically, a REST API follows these principles:

    • Client-server separation: The API should enable the client (or website) and the server to remain separate from one another and continue functioning independently of each other.
    • Caching: REST APIs should use cacheable data, when possible, to improve performance and let the website know which information can be cached.
    • Statelessness: REST APIs can’t store any information about the website they’re connected to on their server, and only the information needed to process a request should be provided.
    • A uniform interface: Requests for resources should be processed in the same way, regardless of their origin. 
    • Layered architecture: REST APIs are built around a layered system, with each layer fulfilling a specific role and working separately from others. This makes the API more secure and easier to update.

    Since a REST API meets these standards, it can provide more security and efficiency. 

    What does the WordPress REST API do?

    WordPress has its own REST API. This enables the platform to communicate with almost every other web application and website, regardless of the programming language they use.  

    With this API, a third-party app will be able to access your WordPress database and pull data from it. In fact, most WordPress plugins and themes use the platform’s REST API to function properly. 

    The WordPress REST API was released as part of the core software in version 4.7. Before then, it was only available as a plugin.

    While the WordPress software is built with PHP, the REST API sends and receives data as JSON (JavaScript Object Notation) objects, which opens up new possibilities for developers.

    What are the most common REST API commands?

    REST APIs are designed to receive and respond to particular requests via HTML commands. 

    The most common commands you’ll use are:

    • GET: You can use this command to fetch a particular resource from the server, like a post or piece of data. 
    • POST: This command lets you modify a resource on the server by adding code.
    • PUT: With this command, you can edit a resource that’s already on the server.
    • DELETE: This command removes a resource from the server.

    These commands are followed by a line that gives more information about the request. These are known as endpoints.

    For instance, if you wanted to retrieve a list of published posts on your site, you would use the following endpoint:

    GET http://mysite.com/wp-json/wp/v2/posts/?status=published

    Let’s look at another example. If you want to add a new page, you would use the following command:

    POST http://mysite.com/wp-json/wp/v2/posts/page

    There are many things you can do with these four commands. You can find a list of endpoints on the WordPress Developer Resources page. 

    Real-world examples of the WordPress REST API

    Now that you have a basic understanding of how the WordPress REST API works, let’s look at some real-life examples, starting with WordPress.com.

    The WordPress.com admin dashboard (called “Calypso”) is built entirely in JavaScript through the REST API.

    WordPress Calypso dashboard, which uses the REST API

    Calypso is a web and desktop app that enables users to add new content, edit existing posts, and more. It uses the REST API to access the data on your WordPress.com site. 

    Another example is the Block Editor. In self-hosted WordPress, the Block Editor uses the REST API to interact with your database and create blocks.

    Many online publications like USA Today also use the WordPress REST API. This enables them to automatically publish articles on other news apps, like Apple News. 

    How to enable and disable the REST API in WordPress

    You don’t need to do anything to enable the REST API — it comes built into WordPress. Later in the post, we’ll show you how to access it.

    While the REST API is a powerful tool for building apps with WordPress, it can make your site susceptible to Distributed Denial-of-Service (DDoS) attacks and malware. Plus, hackers might be able to access your data through the connection with other apps. 

    Disabling the WordPress REST API is not recommended. That’s because doing so can lead to issues with the Block Editor and any plugins on your site.

    If you still want to go ahead and disable it, the easiest way to do this is with a plugin like WPCode.

    WP Code homepage image

    Once you install and activate the plugin on your site, navigate to Code Snippets → Library in your WordPress dashboard.

    WPCode snippets library

    Here, look for an option called Disable WordPress REST API. When you find it, hover over it and select Use snippet.

    using the "disable REST API" snippet

    This will launch a page with a preview of the code.

    editing the WPCode snippet

    If you scroll down to the Insertion box, you can select the Auto-Insert option so that the plugin will automatically apply this code to your site.

    using the auto insert functionality

    Then, scroll back to the top and move the toggle switch from Inactive to Active. Finally, click on Update to make these changes live. 

    How to use the WordPress REST API

    Now, let’s look at how to use the WordPress REST API. We’ve already covered some examples above, but in this section we’ll show you exactly how to access and fetch data. 

    Step 1: Access the REST API

    If you want to fetch data from a live WordPress site, you can access the REST API straight from your browser. All you have to do is enter the following address into the search bar (substituting in your own domain name and extension):

    mysite.com/wp-json/wp/v2

    This will bring up the JSON file of your WordPress site.

    viewing the REST API

    You can then add elements to this URL to access specific data, as we’ll show you in the next step.

    Step 2: Make requests to the REST API

    As we mentioned earlier, you can use endpoints to access particular data on your site. If you want to retrieve a list of all your posts, simply add the endpoint /posts to your address:

    mysite.com/wp-json/wp/v2/posts 

    If you want to retrieve a specific post, you can just add its ID (you’ll find this on the Posts page in your WordPress dashboard):

    mysite.com/wp-json/wp/v2/posts/4567

    Meanwhile, if you want to fetch data about your users, you would use the following request:

    mysite.com/wp-json/wp/v2/users

    These are just simple examples, but there’s a lot more you can do. For instance, you can fetch posts that contain specific terms, change a post’s status from “draft” to “publish,” and more. 

    Step 3: Authenticate your requests

    The WordPress REST API enables you to fetch any type of data on your website, but not all of it is publicly available. In some cases, you’ll need to authenticate your request. 

    To make authenticated requests to the WordPress REST API, you’ll first need to obtain an API key. To do this, navigate to Users → Profile in your WordPress dashboard.

    Then, scroll down to the Application Passwords section. Here, you’ll need to enter a name for your password (for reference) and click on Add New Application Password.

    creating an Application Password in WordPress

    This will generate an API key for you, which you’ll need to use in your requests. For instance, if your API key is “1234567890,” you can include it in an Authorization header like this:

    https://mysite.com/wp-json/wp/v2/posts?Authorization=Bearer1234567890

    Remember to replace the code 1234567890 with the API key you’ve copied and remove any spaces. 

    You can also retrieve a list of posts written by a particular author, with their user ID. You can find their ID by going to the Users section in your WordPress dashboard and clicking on the author’s name. The ID will be displayed in the URL of their author page.

    Let’s say an author’s name is “Joe” and their ID is “123.” In this scenario, you can use the following URL to retrieve a list of all posts written by Joe:

    https://mysite.com/wp-json/wp/v2/posts?author=123&Authorization=Bearer1234567890

    If you can’t find the user’s ID, their profile might have been modified in such a way that the ID is no longer displayed. In this case, you can retrieve a list of all posts written by the user using their login name or email address instead of the ID.

    To do this, you’ll have to use the “slug” parameter instead of the “author” parameter in your request:

    https://mysite.com/wp-json/wp/v2/posts?slug=joe&Authorization=Bearer1234567890

    The “slug” parameter enables you to specify the user’s login name or email address. The WordPress REST API will return a list of all posts written by the user.

    When to use the WordPress REST API

    The WordPress REST API can be used for a wide range of projects. Here are a few examples:

    • Integrating a WordPress site with a mobile app. If you’re a developer, you can use the REST API to retrieve and edit data on a WordPress site from a mobile app. This enables you to build custom apps that interact with your site.
    • Creating custom integrations. Using the WordPress REST API, you can create custom integrations with other software like CRM tools.
    • Building custom scripts. You can use the REST API to automate certain tasks on your WordPress site, like scheduling posts or updating user profiles.

    As you can see, the REST API enables you to integrate WordPress with apps or sites built on other platforms. 

    When not to use the WordPress REST API

    While the WordPress REST API can be a powerful tool, it may not always be the right one for your project. Let’s look at a few reasons why you might not want to use it. 

    As you may recall, the WordPress REST API is built with JavaScript. Therefore, if you’re developing an app that doesn’t support JavaScript, it won’t function properly if you’re using the REST API. 

    Additionally, apps built on JavaScript may not be very accessible. For instance, the way it renders dynamic content may be incompatible with screen readers. As a result, it could make your content inaccessible to users with visual impairments.

    How to secure the WordPress REST API from exploits

    As mentioned earlier, using the WordPress REST API can make your site vulnerable to threats. The API acts as a bridge between two platforms, and hackers may find a way into your website through this connection.

    As such, before you start using the WordPress REST API, it’s important to create a backup of your WordPress site. This way, if something goes wrong, you can restore a recent version of your content. 

    Additionally, you’ll want to make sure that you have sufficient security measures in place. This means using a tool like Jetpack Protect.

    Jetpack Protect homepage

    This plugin comes packed with security features, including malware scanning, vulnerability scanning, and a web application firewall (WAF).

    Furthermore, it’s a good idea to use the REST API on a WordPress staging site before making your changes live. This way, if you accidentally break your website, it won’t affect the user experience on the front end. 

    How to fix common REST API errors and issues

    You may run into some errors when using the WordPress REST API. So, let’s look at some of the most common issues and the steps you can take to resolve them.

    Slow response times and timeouts

    When calling the WordPress REST API, you may encounter slow response times and timeouts. These issues are usually caused by the following factors:

    • Insufficient server resources. Your server might not have enough resources to handle requests made through the REST API. In this case, you’ll need to upgrade to a more powerful WordPress hosting plan.
    • Plugin or theme conflicts. WordPress plugins and themes can sometimes conflict with the REST API. When this happens, try disabling all plugins and switching to a default theme to see if this resolves the issue. If it does, you can reactivate your plugins one at a time to identify the culprit.
    • Size of data. Large data transfers during API calls can cause timeouts. To prevent this, you can try reducing the number of items displayed per page (we’ll show you how to do this later in the post).
    • Database issues. If your WordPress database is not optimized, it can lead to slow response times and timeouts when calling the REST API. You can optimize it by removing unnecessary data and installing an optimization plugin.

    Additionally, you may want to track the performance of your API with a tool like Google Cloud’s operations suite (formerly Stackdriver) and Microsoft’s Application Insights. These tools can provide insight into the performance of the WordPress REST API and help you identify the causes of slow response times.

    403 Forbidden error when calling the REST API

    The 403 Forbidden error is an HTTP status code indicating that the client is not authorized to access the requested resource. Let’s look at some common causes of this error and potential solutions:

    • Incorrect API Key. If the request requires an API key, make sure that the key you’re using is valid and that it’s being passed in the request headers correctly.
    • Invalid nonce. A ‘nonce’ is a random number used once to prevent request forgery. If it’s invalid, it may result in a 403 forbidden error.
    • User permissions. You’ll also want to make sure that you have the necessary permissions to access a specific API endpoint. If you’re not the owner of the website, you may need to ask the administrator to give you the right permissions. 
    • Security plugins. Security plugins can block an API call because it sees it as a security threat. You can whitelist the API endpoint in your plugin settings to resolve this type of issue.
    • Firewall. You might be using a firewall that’s blocking the API request. Make sure that the firewall is set up correctly, or try to disable it while using the API.
    • Server configuration. Some servers are not configured to handle certain API calls, so you might want to reach out to your hosting provider for assistance.

    You can also use your browser’s developer tools to inspect the network requests and request headers. If you use Chrome, simply press Ctrl+Shift+C to open DevTools.  

    Additionally, you can check your server logs for more information about the error. You should be able to access them through your hosting account. If not, you can ask your hosting provider for help. 

    REST API encountered an unexpected result

    The “REST API encountered an unexpected result” error is a common issue. It’s typically caused by the following factors:

    • Permissions. You might not have the right permissions to access the requested resource. If that’s the case, you’ll need to contact the site’s administrator. 
    • URL configuration issue. This error can occur if the API endpoint URL is configured incorrectly. Double-check the URL to ensure that it is correct and that all necessary query parameters are included.
    • Incorrect command. You may be using the wrong command (e.g. GET, POST, PUT, DELETE) for the request. Check the API documentation to make sure that you’re using the correct command for the specific endpoint.
    • Incorrect request format. Make sure that you’re using the right format in your request. In the WordPress REST API, data must be sent as JSON.
    • Wrong endpoint. You might be trying to call an endpoint that doesn’t exist. In this scenario, double-check the endpoint URL to make sure it’s correct.
    • Server-side issues. Your server might be experiencing issues. This is more common with shared hosting plans. If this happens to you, it may be time to upgrade to a server with more resources.

    You may also want to disable your plugins to see if the issue is resolved. As mentioned earlier, some tools may cause compatibility issues with the WordPress REST API. 

    rest_api_init not working

    The “rest_api_init not working” error is another common WordPress REST API error. It’s usually caused by plugin and theme conflicts, as well as limited server resources.

    Still, there are other factors that can lead to the WordPress REST API not working, like:

    • Custom REST API endpoints. If you’re making requests with custom endpoints, make sure that you’re using the correct hooks and functions.
    • .htaccess file. You may need to check your .htaccess file to ensure that it’s set up correctly.
    • CORS error. If you’re trying to make Cross-Origin Requests (CORS) and the WordPress REST API is not working, it might be that the server is not configured to accept them. You may want to contact your hosting provider to see if the server accepts CORS.

    Additionally, you could be using an old WordPress installation that doesn’t support the API. If so, it’s important that you upgrade to the latest version.

    Basic authentication not working

    The “Basic authentication not working” error may occur when trying to call the WordPress REST API using Basic Authentication. Basic Authentication is a simple authentication scheme built into the HTTP protocol. It utilizes a username and password to authenticate someone. 

    Here are some common causes of this error (and how to resolve them):

    • Incorrect credentials. Check the username and password in the request headers to ensure that they’re correct.
    • Secure Sockets Layer (SSL) issue. Make sure that you have a valid SSL certificate installed and that it’s configured correctly. If it isn’t, take a look at our step-by-step guide on how to get a free and valid SSL certificate.
    • HTTP to HTTPS redirects. Some websites are configured to redirect HTTP requests to HTTPS. If the browser is trying to authenticate on HTTP, you might run into this error. Therefore, you’ll want to make sure that you’re running a request on an HTTPS endpoint.

    Like other REST API issues, this error can also be caused by theme and plugin conflicts. Once again, you’ll want to switch to a default theme and deactivate your plugins to troubleshoot the issue.

    If that doesn’t help, you might want to disable your firewall temporarily. This could be blocking your authentication request. 

    If you’re making a CORS, your server may not be configured to accept them. It’s worth checking with your hosting provider to see if there’s anything they can do on their end. 

    Finally, if you’re not the admin of the site, you may not have the correct permissions or role to complete the request. In this case, you’ll need to reach out to the owner of the website. 

    Advanced use cases of the REST API

    Thanks to the WordPress REST API, you can retrieve data from your site using popular frameworks and other programming languages. Let’s take a look at a few examples. 

    How to use the WordPress REST API with React

    React is a popular JavaScript library for building user interfaces. You can use the Node-WPAPI client to make HTTP requests to the WordPress REST API. 

    For instance, to retrieve a list of posts on your WordPress site, you would need to enter the following into Node-WPAPI:

    import WPAPI from 'wpapi';
    
    const wp = new WPAPI({ endpoint: 'http://example.com/wp-json' });
    
    wp.posts().then(posts => {
    
      console.log(posts);
    
    });

    For more information on using the WordPress REST API with React, you can check out the Node-WPAPI documentation.

    How to use the WP REST API with Angular

    Angular is a JavaScript framework for developing web applications. To use it with the WordPress REST API, you’ll need to use the @angular/common/http module.

    For instance, you can input the following code to retrieve a list of posts:

    import { HttpClient } from '@angular/common/http';
    
    @Injectable()
    
    export class PostService {
    
      constructor(private http: HttpClient) {}
    
      getPosts(): Observable<any> {
    
        return this.http.get('http://mysite.com/wp-json/wp/v2/posts');
    
      }
    
    }

    You can check out the Angular documentation for more information on using its HttpClient to make requests to the WordPress REST API. 

    How to use the WordPress REST API with Python

    You can also use the WordPress REST API with Python. This is a popular programming language that can be used to build web applications and other software. 

    To get started, you’ll need to use the Requests library. If you wanted to fetch a list of your WordPress posts, you would enter the following:

    import requests
    
    response = requests.get('http://example.com/wp-json/wp/v2/posts')
    
    posts = response.json()
    
    print(posts)

    You can read the Requests library documentation for more detailed instructions.  

    How does the REST API compare to other WordPress API solutions?

    You may be wondering how the REST API differs from other WordPress API solutions. To give you an idea, we’re going to compare it to some of the most popular alternatives. 

    WordPress REST API vs. AJAX

    The WordPress REST API provides an efficient way to access WordPress data. It enables developers to build custom applications and integrations with WordPress.

    Meanwhile, the WordPress AJAX API is an older method of accessing WordPress data. It was introduced in WordPress 2.0 and enables developers to make asynchronous requests from the front end of the site, using JavaScript. 

    The WordPress AJAX API can be a bit restrictive in terms of functionality, so it’s not recommended for use in complex projects.

    WordPress REST API vs. WPGraphQL

    WPGraphQL is a GraphQL implementation for WordPress that provides an alternate way to access WordPress data. GraphQL is a query language for your API. It enables clients to request exactly the data they need, and nothing more. 

    Unlike the WordPress REST API, WPGraphQL requires a separate application password to be generated for each user who needs access. Plus, it can be a bit slow in delivering content because it uses a more complex query language.

    WordPress REST API vs. XML-RPC

    Introduced in WordPress 1.5, the WordPress XML-RPC API enables you to make remote requests to WordPress using the XML-RPC protocol. 

    XML-RPC is simple and lightweight, and can therefore deliver results faster. The problem is, that like Ajax, it has limited functionality compared to the WordPress REST API. 

    Frequently asked questions about the WordPress REST API

    In this guide, we’ve covered most of the essentials when it comes to the WordPress REST API. But, just in case, let’s look at a few frequently asked questions regarding this powerful tool. 

    Does the WordPress REST API have a return limit?

    By default, the WordPress REST API has a maximum return limit of 100 items per page. That means, if you make a request to an endpoint that returns a list of items (like posts, pages, or users), the API will only display a maximum of 100 items in the response. 

    Fortunately, you can use the “per_page” parameter to increase the limit to a maximum of 500 items per page.

    For example, if you want 200 items per page, you can use the following:

    https://mysite.com/wp-json/wp/v2/posts?per_page=200

    Keep in mind that you can also decrease the number of items displayed per page.

    Can I use the REST API with WooCommerce?

    WooCommerce has its own REST API. The WooCommerce REST API enables you to access and modify data from your WooCommerce store. This includes information on products, orders, and customers. Plus, you can use the WooCommerce REST API to integrate WooCommerce with other ecommerce platforms.

    Get started with the WordPress REST API

    The WordPress REST API enables you to integrate your site with other apps and third-party tools. Web developers can use it to fetch data for single-page applications, connect WordPress to a mobile app, and much more.

    Additionally, you can use the WordPress REST API with other frameworks and programming languages, including React, Angular, and Python. Although the WordPress REST API is a powerful and dependable tool, it’s still important to back up your site and use a security tool to prevent attacks through these connections.

    With Jetpack Protect, you can secure your WordPress site against malware and hackers, and use the WordPress REST API in a safer environment. 

  • How to Add & Use jQuery Scripts in WordPress

    Interactive page elements like dynamic search bars, advanced product filters, and sliders can make your site more user-friendly and engaging. But it’s impossible to create any of these features without using JavaScript or installing WordPress plugins.

    Luckily, you can easily create JavaScript design elements by using jQuery in WordPress. You can do this manually or use a plugin to speed up the process.

    In this post, we’ll introduce you to jQuery and discuss why you may want to use it. Then, we’ll show you two ways to add custom jQuery scripts to your WordPress site and review some frequently asked questions. 

    What is jQuery? (and why you may want to use it)

    Before you learn how to add jQuery scripts in WordPress, you’ll need a baseline understanding of jQuery itself. 

    In a nutshell, jQuery is a lightweight, open-source JavaScript library that simplifies the way you can write and use this coding language.

    jQuery code homepage with information about the language

    It enables you to easily modify and enhance WordPress themes and plugins using JavaScript. This feature can be extremely helpful since JavaScript is essential for many features. 

    For example, you need JavaScript for Ajax, event handling, and DOM transversal/manipulation. Ajax functionality, in particular, is practical and popular. Web developers use it to create instant search loading and advanced ecommerce product filtering.

    Robert August website showing product filters that are triggered using jQuery

    An action from the user, like a click or a search, often triggers these JavaScript features. You also need jQuery to create additional client-side features like sliders, lightbox pop-ups, and more.

    Is jQuery included in WordPress by default?

    jQuery is such a useful and popular resource that comes included in your WordPress installation by default. You just need to know how to use it! In the next sections, we’ll teach you how to do this. 

    What to do before adding jQuery scripts to WordPress

    We’ll soon explain how you can add jQuery scripts in WordPress. But first, you should do a few things to safeguard your website before attempting to modify its core files.

    Most importantly, it’s always recommended to create a backup of your site. That’s because even the slightest coding error to critical website files can do serious harm. When you make backups, you can easily restore your site to its previous state in an emergency.

    If you’re not sure how to back up your WordPress site, or you’re just looking for a tool to streamline the process, Jetpack VaultPress Backup is an excellent option.

    Jetpack VaultPress Backup landing page

    Jetpack VaultPress Backup automatically saves every change on your site. Then you can use one-click restores to recover your content quickly. Jetpack even allows you to restore your site from the Jetpack mobile app. Furthermore, if you run into any issues, you can get assistance from the best-in-class customer support — Happiness Engineers! 

    To further protect your website, it’s also worth creating a WordPress staging site. Then, you can test your changes before pushing them live.

    How to add custom jQuery scripts to WordPress

    Now that you know more about jQuery and preparing your site for major changes, let’s discuss two ways to add custom jQuery scripts to WordPress!

    Method 1: Add jQuery manually

    First, we’ll show you how to add jQuery to WordPress manually. This method might be for you if you have some development experience and want full control over the process. 

    It’s worth using a child theme so that any changes you make won’t be overridden when you update your theme. 

    Step 1: Go into Compatibility Mode

    One of the great things about jQuery is that it allows you to use some familiar shortcuts when coding. Most notably, you can use the $ symbol to represent jQuery. This can save you a lot of time, but some other libraries use this shortcut to represent something different.

    Therefore, you’ll want to go into Compatibility Mode and create a unique alias for jQuery. This way, you will avoid conflicts with other libraries. 

    You can do this using the following code:

    <!-- Putting jQuery into no-conflict mode. -->
    
    http://prototype.js
    
    http://jquery.js
    
    <script>
    
    var $j = jQuery.noConflict();
    
    // $j is now an alias to the jQuery function; creating the new alias is optional.
    
    $j(document).ready(function() {
    
        $j( "div" ).hide();
    
    });
    
    // The $ variable now has the prototype meaning, which is a shortcut for
    
    // document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
    
    window.onload = function() {
    
        var mainDiv = $( "main" );
    
    }
    
    </script>

    When you action the above script, you’ll be able to use $j as a shortcut instead of $. Alternatively, you could use the following:

    <!-- Loading jQuery before other libraries. -->
    
    http://jquery.js
    
    http://prototype.js
    
    <script>
    
    // Use full jQuery function name to reference jQuery.
    
    jQuery( document ).ready(function() {
    
        jQuery( "div" ).hide();
    
    });
    
    // Use the $ variable as defined in prototype.js
    
    window.onload = function() {
    
        var mainDiv = $( "main" );
    
    };
    
    </script>

    This code snippet will simply prevent any conflicts. Still, you’ll need to use the full name, jQuery, instead of a shortcut.

    Step 2: Make a script file

    Now that you have the code you need, you’re ready to make a script file. Create a file and give it a descriptive name like “my_new_script_file.js”. Make sure to use the .js extension and add your preferred compatibility code snippet at the top.

    At this point, you’ll need to access and edit your theme files, which have their unique folders within your website files. 

    Start by connecting to your website using your file manager or a free File Transfer Protocol (FTP) client like FileZilla.

    FileZilla homepage

    Then, open your root directory. This should be named something like public_html or simply public. Alternatively, it could just be your website’s name.

    Next, locate your active theme’s folder and create a new subfolder. Call it /js/. 

    Finally, add your new script file to this subfolder. Its contents will differ depending on the feature you’re trying to implement. 

    Step 3: Add a jQuery script to your functions.php file

    Next, you’ll need to locate your theme’s functions.php file. Both parent and child themes should have one. This is where all manual customizations happen.

    Since JavaScript requires enqueuing, you’ll need to use the wp_enqueue_script() function. Your code might look something like this:

    function my_theme_scripts() {
    
        wp_enqueue_script( 'my_new_script_file', get_template_directory_uri() . '/js/my_new_script_file.js', array( 'jquery' ), '1.0.0', true );
    
    }
    
    add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );

    Make sure to substitute the name of your unique script file and add it to functions.php. This will tell your theme file to use the script file you created in the previous step.

    Method 2: Add jQuery with a WordPress plugin

    As we have just seen, adding jQuery manually can be time-consuming and a bit risky, especially if you’re not familiar with editing code in WordPress. So, now we’ll show you how to add jQuery with a WordPress plugin.

    Step 1: Install a jQuery plugin

    First, you’ll need to choose a jQuery plugin. Two of the most popular options are Simple Custom CSS and JS and Advanced Custom Fields.

    Advanced Custom Fields plugin page

    For this tutorial, we’ll use Advanced Custom Fields. This tool helps you create engaging, interactive features with custom block types

    The free version has plenty of useful block types for adding elements like button groups, Google Maps, color pickers, oEmbed, and much more. If you want all 30 custom blocks, though, you’ll need to upgrade to the paid version of Advanced Custom Fields. 

    Once you’ve selected your preferred plan, simply install and activate the plugin as you usually would. Add any license keys under your plugin settings.

    Step 2: Create a new custom field

    After you’ve installed and activated the plugin, go to Custom Fields → Add New.

    adding a new custom field

    Here, you’ll need to create your first field group. Give it a title next to Add New Field Group. Then, click on Save Changes.

    Now, you can start editing the new field. You can expand the options by clicking on Edit below the label.

    adding a new field group

    First, open up the dropdown menu for Field Type, and select one.

    selecting a field type

    Then, fill in the Field Label, Field Name, etc. If you continue to scroll down, you can modify additional settings like Location Rules and Presentation.

    setting location rules for a field

    Depending on the location you select, you’ll be able to view your new custom block there. In the Block Editor, you can identify the block by the label you designated under Field Label.

    When you’re finished, click on Save Changes. You can select the + Add Field button and repeat this process. After that, simply go to one of the locations you chose for your field and start customizing it! 

    How to defer jQuery in WordPress

    As we’ve discussed, there are plenty of reasons to use JavaScript and jQuery in WordPress. In fact, they’re crucial for certain interactive features that many users take for granted.

    But the downside is that these sophisticated client-side elements might slow down your website. So, you may want to automatically defer JavaScript (and, by extension, jQuery) when your WordPress site loads. 

    By deferring JavaScript, all the main elements on your site will load before the less critical JavaScript features. Of course, your site visitors probably won’t notice this happening, but it will likely improve their user experience (UX) because the page will appear to load faster.

    If you want to automatically defer jQuery on your website, you can use Jetpack Boost to do so.

    Jetpack Boost homepage

    This plugin can drastically improve your website’s performance overall. As a result, you’ll be able to maintain all your preferred JavaScript features without compromising page speed.

    In addition to deferring non-essential JavaScript, Jetpack Boost can optimize CSS loading and apply lazy image loading (among other performance optimizations). Using this tool, you can improve your Core Web Vitals scores and boost your site’s visibility in search results.

    Frequently asked questions about jQuery in WordPress

    Hopefully, we’ve clarified most of your doubts about jQuery in WordPress. Still, if we missed something, here are some frequently asked questions!

    Can you change the jQuery version used in WordPress?

    Sometimes themes and plugins can replace or add jQuery versions to your site. Therefore, it’s important to ensure that your version is always up-to-date. You can easily do this using a plugin like jQuery Updater or Version Control for jQuery.

    Where can I check the jQuery version on my WordPress site?

    You can usually check your jQuery version in a browser. In Google Chrome, simply navigate to your website on the front end. Then, go to View → Developer → JavaScript Console.

    Enter jQuery.fn.jquery, and the console should return your site’s current version. 

    Can you completely remove jQuery from WordPress?

    The short answer is: yes. If you discover that using JavaScript on your site negatively impacts its performance, you may want to remove or ‘deregister’ jQuery. 

    To do this, simply add the following code to your functions.php file:

    // Remove jQuery
    
    function vpsb_remove_jquery() {
    
        if (!is_admin()) {
    
            wp_deregister_script('jquery');
    
            wp_register_script('jquery', false);
    
        }
    
    }
    
    add_action('init', 'vpsb_remove_jquery');

    Keep in mind you should only completely remove jQuery from your site if it’s drastically slowing down your pages. This likely won’t happen, though, since jQuery already optimizes heavier JavaScript code.

    If your site’s speed has deteriorated after adding jQuery, a better alternative would be to use a solution like Jetpack Boost. It can defer non-essential JavaScript.

    Can you replace jQuery with vanilla JavaScript?

    It is possible to replace jQuery with vanilla JavaScript. But, it might prove challenging if you don’t have much development experience. So, you should consider hiring a developer if you need to do this.

    Once again, it’s worth noting that replacing jQuery with vanilla JavaScript is probably unnecessary because jQuery already provides optimal JavaScript code. Most of the time, the minor performance effects of jQuery are usually worth the trouble, and deferring is typically a better option.

    If you decide to go this route, it’s worth checking out this guide to adding JavaScript to WordPress. It can help you with the process.

    Using jQuery in WordPress

    Using complex JavaScript for engaging features on your site can drastically improve the UX and advance your goals. Unfortunately, you may not have the time or development skills to create these interactive elements from scratch. The good news is that you can use jQuery scripts to make this process easier.

    To recap, there are two ways you can add jQuery to WordPress. First, you’re able to do this manually by going into Compatibility Mode and creating a script file. Then, add your new script to your functions.php file. Alternatively, you could use a plugin like Advanced Custom Fields to speed up the process and eliminate the need for manual coding.

    When you use jQuery to add sophisticated design elements to your website, you can improve the UX and impress your visitors. But multiple interactive features could harm the performance of your web pages. Fortunately, Jetpack Boost can help optimize your site’s speed.

  • How to Add CAPTCHA to a WordPress Contact Form

    Most websites — including those using WordPress — deal with spam on a daily basis. Even if you just created your first site a few weeks ago, chances are you’re already facing the reality of spam comments, queries, account sign-ups, and more. 

    CAPTCHAs can effectively mitigate unwanted spam, especially if it’s coming from your contact forms. But while one can help alleviate problems with spam, you’ll likely encounter the unintended consequence of a more difficult experience for your real visitors.  

    That’s why many sites have chosen to use Akismet — a more streamlined anti-spam solution for WordPress — instead. 

    So, which option is right for your site?

    In this article, we’ll start by talking about the downsides and alternatives to using CAPTCHAs, so you get the full picture. Then, we’ll show you how to protect your WordPress contact forms both with and without CAPTCHAs.

    What is a CAPTCHA? 

    CAPTCHA stands for “Completely Automated Public Turing Test to Tell Computers and Humans Apart.” Phew!

    The earliest versions presented users with distorted text they’d have to decipher. Because it was difficult to complete, it could fairly accurately tell humans and computers apart. 

    What are the downsides of using a CAPTCHA?

    To put it simply, people hate CAPTCHAs. That’s not a matter of opinion, either. A Stanford study shows that only 71 percent of users attempt to solve CAPTCHAs when they run into them. The rest of them outright leave the page. 

    Another study from Moz confirms those numbers. It shows that, on average, 30 percent of users leave pages with CAPTCHAs, either while trying to solve them or before trying. The same study states that simply adding a CAPTCHA can lower your site’s conversion rates by 3.2 percent.

    If you’re relatively tech-savvy, you probably don’t struggle at all with solving CAPTCHAs. But, a lot of the users that decide to leave a page when they see one do so because CAPTCHAs are designed to be difficult to solve.

    According to Stanford, solving a video CAPTCHA can take up to ten seconds on average and audio CAPTCHAs have a staggering failure rate of 50 percent. Even regular image CAPTCHAs can be difficult to solve since they intentionally obfuscate letters and symbols. Some pages even ask you to resolve multiple CAPTCHAs before letting you proceed.

    To be fair, CAPTCHAs work. They provide a functional solution to a problem that most websites struggle to deal with. 

    The problem is, using a CAPTCHA shifts the responsibility to users. It’s like asking store customers to prove they’re not thieves before they can make a purchase. Furthermore, it’s not a good option when it comes to accessibility standards. That’s because it might alienate users with vision or hearing impairments. Since there are indeed alternatives to CAPTCHAs, you might want to consider which option to use before implementing them.

    What are the different kinds of CAPTCHAs?

    There are lots of types of CAPTCHAs. Most websites use reCAPTCHA, which is a free solution (for up to 1,000,000 assessments per month) from Google. When you run into a contact form that uses reCAPTCHA, you’ll need to check a box that says, “I am not a robot.”

    example of a CAPTCHA with a checkbox next to "I am not a robot."

    If the service detects any suspicious movement or activity with your connection, you’ll need to solve an image puzzle. In most cases, the puzzle will ask you to identify multiple similar elements from a cluster of images. Depending on the case, you might need to solve multiple image puzzles before submitting a form.

    Aside from reCAPTCHA, you might also run into audio or video CAPTCHAs. These tend to be worse (from a user standpoint) because you’re required to watch and/or listen in full before you can solve the puzzle. In a lot of cases, this might not even be possible if you’re somewhere where you can’t listen to audio, don’t have a pair of headphones on hand, or have an impairment.

    The ideal CAPTCHA is one that requires very little work from users while still providing a solid level of protection from spam. It should also be accessible to as many people as possible. Some CAPTCHA alternatives, like Akismet, can provide this.

    What’s the best CAPTCHA alternative?

    If you want to eliminate spam from your WordPress site, but don’t want to push away visitors with complicated, annoying tests, the best CAPTCHA alternative is Akismet. 

    Meet Akismet: The non-intrusive spam blocker

    Akismet is one of the most popular WordPress tools on the market. It’s designed to help you prevent spam without adding complications for visitors, by identifying spam and malicious comments submitted through your site’s forms. 

    Aksimet homepage with options to sign up for a plan

    It’s ‘non-intrusive’ because Akismet can protect your website from spam without using CAPTCHAs. The service analyzes every comment and form submission on your website to see if it matches known spam or malicious IP addresses, or if it follows patterns that raise red flags (like linking to unrelated third-party sites).

    You can configure Akismet to automatically delete these submissions or let you review them to check if they’re from real visitors. In either case, visitors never see a CAPTCHA when you’re using Akismet. Your site remains protected, and the user experience improves drastically.

    Everything happens in the background. There’s nothing special for visitors to fill out. No puzzle, no audio to listen to, no stop signs to identify. Real visitors can go on their way none-the-wiser. Spam submissions are then identified and deleted or sorted for you to review later. 

    How to add Akismet to a WordPress contact form

    Adding Akismet to WordPress contact forms is easy. You can do it in just a few steps. Still, the process can vary slightly depending on the type of contact form or plugin you’re using, so let’s discuss how it works!

    Step 1: Install and activate Akismet

    Non-commercial sites can use Akismet for free to stop spam comments and nefarious contact form submissions. To get started, you’ll need to install and activate the plugin. 

    Go to the Plugins tab in your WordPress dashboard. Then, click on Add New and use the search tool to look for the Akismet plugin. In a lot of cases, it will be an option among the top ‘featured’ plugins.

    When you find the plugin, click on Install → Activate. Once the plugin is active, go to Settings → Akismet Anti-Spam. Under the Settings section, you’ll see a field where you need to enter an API key.

    To get this key, go to the Akismet website and sign up for an account. After you sign up, you’ll get access to the Akismet dashboard. Go to the My Account tab and select the Add Subscription option.

    Akismet subscriptions panel

    On the next page, you’ll be able to choose which plan you want to use. The Personal plan uses a pay-what-you-want model, so you can sign up for free and use it for a single website. Keep in mind that you can only sign up for this free plan if you don’t run ads, sell products, or promote a business through your website.

    After confirming your subscription, you’ll get access to an API key, which you can see in the My Account tab. Copy the key and return to the Settings → Akismet Anti-Spam screen in the WordPress dashboard. Paste it in the API Key field.

    adding an API key to Akismet settings

    Click on Save Changes and that’s it. By default, Akismet will block comment spam and send it to a queue where you can review submissions in the dashboard. There’s an extra step involved if you want to use Akismet with a contact form.

    Step 2: Integrate Akismet with your contact form

    WordPress doesn’t offer contact form functionality out-of-the-box. That means most users rely on plugins to implement these types of forms on their websites. This step will depend on what contact form plugin you’re using. 

    Akismet works with most popular WordPress contact form plugins. Some plugins, like Formidable Forms and WPForms include built-in support for Akismet. With either plugin, you just need to enable the Akismet spam protection setting for each individual form.

    setting up Akismet form integration

    Other plugins, like Gravity Forms, require you to set up Akismet add-ons to add spam protection to their forms. Finally, there are some tools, like Contact Form 7 and Ninja Forms which require you to add code snippets to your forms to enable support for Akismet. Fortunately, all three of these methods are pretty straightforward.

    For the easiest solution, consider using Jetpack’s WordPress contact form functionality

    Read more: How to use Akismet with WordPress contact forms

    Step 3: Configure Akismet’s anti-spam settings

    Akismet is pretty much a plug-and-play tool, which can be appealing if you’re looking for something quick and easy. In any case, it also gives you control over how you want to handle contact form spam. 

    By default, the plugin sends comments it flags as spam to a special ‘queue’ where you can review them (in the Comments section of the dashboard). Alternatively, you can configure Akismet to discard spam completely, so you don’t have to deal with it. 

    To do this, go to Settings → Akismet Anti-Spam and search for the Settings section. The option you’re looking for appears under Strictness.

    strictness settings in Akismet

    Akismet does a great job of separating spam messages from real ones. That means you can choose to discard contact form spam without worrying too much about it. If you want to preserve every message to play it safe, opt for the Always put spam in the Spam folder for review setting.

    Keep in mind that Akismet only stores spam comments for 15 days. After that, it deletes them automatically. This means you’ll want to review the queue every week or every two weeks at the most.

    How to add CAPTCHA to a WordPress contact form

    The process of adding CAPTCHAs to WordPress contact forms will depend on what service you’re using. Since reCAPTCHA is the most popular CAPTCHA solution on the web, we’ll show you how to integrate it with a WordPress contact form.

    Step 1: Sign up for a reCAPTCHA account

    If you already have a Google account, you can access reCAPTCHA right away. Simply visit Google.com/reCAPTCHA and select the v3 Admin Console option in the primary navigation menu.

    Google reCAPTCHA homepage

    Click on the plus sign icon in the reCAPTCHA dashboard and enter a label for your website. This can be any unique identifier. Then, choose what type of reCAPTCHA you want to use for your site. 

    The most common type of CAPTCHA is reCAPTCHA v2, which forces users to solve a challenge or a puzzle to make a submission.

    settings for reCAPTCHA

    Next up, look for the Domains field. Enter the domain of the website where you want to use reCAPTCHA.

    choosign a domain

    After entering the domain, you’ll need to review reCAPTCHA’s terms of service, agree to them if you do, and submit the form. Then, reCAPTCHA will provide you with a site and a secret key. You’ll need both for the following steps, so keep the tab open or copy and paste them somewhere safe.

    Step 2: Find a plugin that’s compatible with reCAPTCHA

    There are a handful of WordPress contact form plugins that are compatible with reCAPTCHA. But, not all of them support it out-of-the-box. Some plugins will simply need an add-on, but a lot of them require you to add custom code directly to individual contact forms in order to display challenges.

    What’s more, reCAPTCHA doesn’t offer documentation showing which WordPress plugins are compatible with it. However, the most popular contact form plugins will likely have an integration method.

    If you’re not sure whether the plugin you’re using is compatible with reCAPTCHA, you should check its documentation. If you discover that it’s compatible, you should be able to find instructions on how to implement the anti-spam system with your contact forms.

    Frequently asked questions about CAPTCHA and WordPress forms

    If you have any questions left about CAPTCHAs and how they work, this section will answer them. Let’s start by reviewing what CAPTCHAs are.

    What is CAPTCHA?

    A CAPTCHA is a kind of test designed for users to prove that they’re humans and not bots. This is necessary because most websites with comment sections or contact forms have to deal with a lot of bots and spammers.

    These bots tend to leave spam comments pointing toward other websites or try to find vulnerabilities in forms. CAPTCHAs help stop them since they require some level of human ingenuity to solve. Typically, CAPTCHAs involve image puzzles, but they can also use video or audio.

    What is reCAPTCHA?

    reCAPTCHA is a CAPTCHA tool offered by Google. It functions as a ‘freemium’ service that provides up to 1,000,000 assessments per month in as many forms as you need. 

    If you implement reCAPTCHA, visitors need to check a box before submitting a form to confirm they are human. The service may request additional confirmation in the form of visual tests if it detects any anomalies.

    What is contact form spam?

    Spam is everywhere online, from comment sections to contact forms. Every time you create a form, you open another venue for spam. There are a lot of bots and people dedicated to using forms to submit spam, ranging from promoting their own content to sharing links to malicious sites.

    Contact form spam is any submission that’s not designed to fulfill the purpose of the form but to bypass it or to trick you into taking an action with negative consequences. This type of spam is typically easy to spot, but dealing with it can take up a lot of time you could otherwise spend responding to legitimate queries.

    Is CAPTCHA the best solution for contact form spam?

    CAPTCHAs are an effective way to reduce contact form and other types of spam. But, research shows that users react very negatively to CAPTCHAs. On average, 30 percent of users leave a page when they see a CAPTCHA.

    Although CAPTCHAs work, you need to decide whether they’re worth the loss of legitimate visitors and potential conversions. Moreover, there are alternatives to CAPTCHAs that are less intrusive, like Akismet. Alternative anti-spam tools that don’t force visitors to solve puzzles will offer a much better experience than CAPTCHAs.

    Akismet vs CAPTCHA: Which one should I choose?

    The answer to this question depends on what type of website you’re running and the user experience you want to offer. For ecommerce sites, the loss in visitors and conversions that CAPTCHAs often cause can result in a significant loss of revenue.

    For contact forms specifically, using regular CAPTCHAs means you’ll lose out on some potential queries. Solutions like Akismet are less intrusive and just as effective. If you’re using WordPress, implementing Akismet is remarkably simple, which makes it a better solution than CAPTCHAs.

    Will Akismet work with my contact form plugin?

    Akismet works with most WordPress contact form plugins (at least the well-known options). Some plugins offer out-of-the-box compatibility with Akismet whereas others require you to install add-ons. For some plugins, you may need to add custom code to your forms, but the process is usually very simple.

    How many WordPress websites trust Akismet?

    Akismet is one of the most popular WordPress plugins in the world, bar none. There are over five million active installations of Akismet at the moment, and that number keeps rising.

    In fact, many web hosts offer Akismet as one of a handful of plugins that come pre-installed with their WordPress setups. That’s because using Akismet from the get-go can help you reduce the level of spam you deal with and, thus, secure your website.

    If you want to implement an anti-spam solution that doesn’t require you to force visitors to solve puzzles, Akismet is the way to go. Millions of users already trust Akismet to protect their sites, and it’s free for non-commercial sites. That’s why we listed it as one of the must-have plugins for WordPress sites.

    Use Akismet to prevent spam in WordPress

    If you have a website with forms, you probably need to implement some sort of spam protection. For a long time, CAPTCHAs have been the industry go-to. They’re relatively easy to implement, and they get the job done. Still, it’s unwise to ignore the negative effect they have on the user experience. Simply put, people do not like CAPTCHAs.

    For the best spam protection without annoying site visitors, you should consider an alternative like Akismet. It’s cost-effective and simple to get started.

    Want to keep your customers happy while also protecting your WordPress site from spammers and bots? Sign up for Akismet today!

  • How to Export and Import a WordPress Site (3 Best Methods)

    Are you looking to export a WordPress site? Perhaps you want to create a full site backup or move your content to a new server or web host. If you’re not an experienced developer, this process might seem challenging.

    Fortunately, exporting your WordPress website isn’t too complicated. Tech-savvy users can get the job done with Secure File Transfer Protocol (SFTP) and phpMyAdmin. Beginners, and really anyone looking to save time and effort, can handle the export and import process quite easily using a tool like Jetpack VaultPress Backup.

    Let’s look at why you might want to export and import a WordPress site. Then, we’ll show you three different methods you can choose between. 

    Why you might want to export a WordPress site

    There are many reasons you might consider exporting a WordPress site. For starters, it’s a great way to make a full backup of your site

    Then, you can store your backup securely in a remote location separate from the server where you host your site. Here, your backup will remain safe and intact even if the server is attacked or goes down. Plus, you won’t be using any more of your server resources. If you run into any problems with your WordPress website, you’ll be able to restore a functional version to keep things up and running.

    Additionally, you might migrate a WordPress site to a new web host. Or, you may want to move from a localhost to a live server

    It’s always a good idea to check whether your new host offers migration assistance as part of their services. That way, the host can take care of the entire process, and you can simply log in to your new site when it’s ready. Otherwise, you’ll need to perform a manual migration (we’ll explain this later in the tutorial). 

    What is the easiest way to export a WordPress site?

    In the tutorial section of this article, we’re going to discuss three ways to export a WordPress site. Firstly, you can use the built-in WordPress export tool. This approach is simple enough to use, but it doesn’t transfer theme, plugin, or database files.

    You also have the option to export your site manually using phpMyAdmin. But this is not a beginner-friendly method, requiring at least some technical knowledge.

    Overall, the easiest way to export a WordPress site is to use Jetpack VaultPress Backup. It’s a simple, fast solution developed by Automattic (the people behind WordPress.com). Since it’s built on the same infrastructure as WordPress.com, you can expect smooth, reliable performance without plugin or host conflicts.

    What to consider before exporting your site

    With any significant change to your site, there’s a slight risk involved. Preparing for the export process can minimize the chance of something going wrong and put your website in a better position to recover. 

    Here are some main factors to consider before exporting your WordPress site:

    • The type of export. Whichever method you choose, you’ll need to ensure that it enables you to export the content you need. For instance, some approaches don’t allow you to export theme files, database files, or plugins. You might also utilize this opportunity to streamline your website by reducing the number of plugins you use.
    • The time of day. It’s important to consider what time of day you’ll carry out the export. This is especially relevant for high-traffic websites since you don’t want to disrupt your visitors. Therefore, it’s a good idea to avoid peak traffic and schedule the import/export for a slow period. 
    • Conflicts. The best way to avoid conflicts during your export is to upgrade to the latest PHP version. Using a well-coded backup plugin like Jetpack to handle the export can also ensure that the software is compatible and prevent glitches.

    By following the tips above, you can give your WordPress website a better chance of a smooth, successful export.

    How to export and import your WordPress site (3 best methods)

    Now let’s discuss three different ways to export a WordPress site. We’ll start with the simplest solution and end with the method that requires the most technical experience.

    1. Use a tool like Jetpack VaultPress Backup

    Jetpack VaultPress Backup takes the hassle out of migrations. As a tried-and-tested solution, it offers easy restores, remote storage, and stellar support.

    Jetpack VaultPress Backup homepage

    Better yet, backups can include website files, database tables, and customer and order data. This makes it an excellent choice for many types of sites, particularly ecommerce stores.

    To get started, you’ll need to install and activate the Jetpack plugin in WordPress. Navigate to Plugins → Add New and then search for “Jetpack.”

    Jetpack plugin listed in the WordPress dashboard

    This free version of Jetpack provides a number of security and optimization features. Hit Install → Activate. Then, you’ll need to approve the connection to your WordPress site. You can use an existing WordPress.com account or create one once the plugin is active.

    To get Jetpack VaultPress Backup, you’ll need to upgrade to the Jetpack plan that best suits your needs. For instance, you might opt for Jetpack Security or Jetpack Complete, which give you access to a variety of performance and security tools. But, for exporting a WordPress site, you’ll only need the VaultPress Backup plan. 

    Once you’ve found a plan and activated VaultPress Backup, head to Settings → General in your WordPress.com account. Here, scroll down to the bottom of the page and select Clone.

    option to clone your WordPress site

    Check that all your website details are correct. If so, hit Continue

    confirming the WordPress clone settings

    Enter your new destination site title and URL. This is the place you’re moving your site

    setting the destination site URL

    Next, enter your new server credentials. These include your username, password, and port.

    entering server credentials

    You can often find these server credentials yourself by logging into your hosting provider’s control panel. If you’re unsure about what these are, you can check with your web host. We’ve created a pre-written email that you can share with your host to make this easier.

    Now, enter the destination WordPress path. This is where your site files will be stored. Generally, it will look something like public_html. Again, if you’re unsure, check with your new web host.

    Then, hit Save.

    To use your most recent backup, select Clone current state, or you can use an earlier backup if you wish. When you’re ready to begin the cloning process, click on Yep! Begin Cloning. Once the process is finished, you’ll see a confirmation message.

    successful clone message

    Before pointing your domain name to your new host, you’ll need to verify that the content loads correctly and that all functionality works as it should. Otherwise, you risk losing traffic and/or sales if your site is glitchy or doesn’t load.

    To do this, you’ll need to change your hosts file. This exact process will vary based on your operating system, but it will enable you to test out functionality and design elements before pointing your domain name.

    If everything looks as it should, you can go ahead and update your DNS settings!

    2. Use the built-in WordPress export tool

    This method doesn’t require adding any new tool or plugin to your WordPress dashboard. Unfortunately, it doesn’t export theme files, plugins, or database tables. Therefore, it’s only viable if you want to move content to a different WordPress site, or back up your posts and pages. 

    To begin, navigate to your WordPress admin area. Once here, select Tools → Export. You’ll be taken to a new screen that looks like this.

    choosing the elements to export in WordPress

    Select All content to export your entire website. Or, you can choose specific types of content, like pages, posts, comments, or menus. 

    Then, hit Download Export File to download the file to your computer. This creates a copy of your site without affecting your existing website. 

    Next, switch to the WordPress site where you want to import your file. Log in to your new dashboard and go to Tools → Import.

    import options in WordPress

    If your exported file comes from WordPress, head down to the bottom of the page to find the relevant section. You’ll notice that you can also import files from other platforms like LiveJournal, Tumblr, and WooCommerce. 

    Once you’re here, click on Install Now and then Run Importer.

    option to run WordPress Importer

    This will take you to a new page where you can upload your exported file.

    settings for importing into WordPress

    Choose the file from your computer and hit Upload file and import to start the import process. This should take just a few minutes. 

    3. Use phpMyAdmin and SFTP to export your site manually 

    This is the most difficult of the three methods. Therefore, it’s only recommended for experienced WordPress users. You might use this method if you don’t have access to WordPress, in special circumstances like having files stored outside the standard WordPress installation, or if you encounter an unexpected issue with another method.

    Note: If you have the Jetpack plugin installed on your site, you’ll want to either disconnect Jetpack from your current WordPress installation or exclude the Jetpack plugin files when migrating. Otherwise, you might end up with an Identity Crisis. If you choose the second option, you’ll just want to reinstall and reconnect Jetpack in your WordPress dashboard after the migration.

    To start, you’ll need to connect to your existing hosting account using an SFTP client like FileZilla

    You’ll need your SFTP credentials like your host, username, password, and port. You should be able to find these details in your hosting account.

    Once you’ve connected to your site with SFTP, locate the root folder of your website. Typically, this is labeled public_html, although sometimes, it may be named after your site’s domain.

    viewing the public_html folder in an FTP client

    Drag the files in this folder from the right panel (your server) to a selected folder in the left panel (your computer). This will download all the files to your device, and could take a little while if your website contains a lot of data.

    At this point, log in to your hosting provider’s control panel and access phpMyAdmin. The interface will look different depending on your web host, but it’s typically found under Databases.

    opening phpMyAdmin from a hosting account

    Next, click on Export to download a file to your computer. You’ll also need to choose SQL as the format.

    Then, head back to FileZilla and connect to your new server using your new SFTP credentials. Again, you can get these from your host if you’re not sure where to find them. 

    This time, you’ll drag the files from your computer (left panel) to the new server (right panel). Wait for the file migration process to finish.

    You’ll now need to create a new, blank database. This process can vary a bit depending on your hosting provider, but you’ll need to establish a database name, username, and password. Make sure to save this information, as you’ll need it in a minute.

    Navigate to your database in phpMyAdmin, click on the Import tab, then upload the SQL file you downloaded earlier.

    importing a database file

    Click the Go button. Now, all you need to do is tell your migrated WordPress site how to access the new database. You’ll do this through the wp-config.php file.

    Navigate to this file using your hosting control panel or via FTP, then look for the following lines of code:

    /** The name of the database for WordPress */
    
    define( 'DB_NAME', 'sample1234' );
    
    /** Database username */
    
    define( 'DB_USER', 'user1234' );
    
    /** Database password */
    
    define( 'DB_PASSWORD', 'password1234' );

    Change the information for DB_Name, DB_User, and DB_Password based on the data you saved earlier, then save the file. 

    Finally, point your nameservers to your new hosting provider. And you’re done!!

    Frequently asked questions

    By now, you should hopefully have a good understanding of the WordPress export and import process. If you have any remaining questions, we’ll tackle them here!

    Is a WordPress export necessary when changing domains?

    No, you won’t typically need to export your WordPress site when switching domain names. You’ll only need to do this if moving to a different host or server.

    Are there any extra steps when exporting a WooCommerce site?

    Generally, no. If you export your site using Jetpack VaultPress Backup or FTP, all the WooCommerce information will be included. You can follow the steps above as written.

    However, if you’re using the WordPress built-in tool, you’ll see some additional options to manually export products, variations, orders, refunds, and coupons.

    extra export options for WooCommerce

    Export your WordPress site quickly and easily

    Exporting your WordPress site is helpful if you want to move it to a new server or web host. It’s also beneficial if you need to back up your files. Although this process may seem intimidating, it’s much easier when you use a plugin to take care of the process.

    To recap, here are three methods to export and import a WordPress site:

    1. Use a tool like Jetpack VaultPress Backup.
    2. Use the built-in WordPress export tool.
    3. Use phpMyAdmin and SFTP to export your site manually.

    Jetpack VaultPress Backup will create real-time backups of your website and enable you to easily restore them. Better yet, you can back up all your site files, including customer data and database files. Get started with Jetpack today!

  • How to Upload a Video to WordPress & Add it to a Page or Post

    There are many reasons you may want to upload a video in WordPress. Whether you’re a professional videographer or a food blogger with an amateur cooking show, you’ll need a simple way to post audiovisual content on your site. 

    There are a couple of different ways you can add a video to a WordPress page or post. You could embed one from a video hosting service like Jetpack VideoPress or upload and add it directly from your site’s hosting server. Each method has its pros and cons, which we’ll cover in more detail in our tutorial. 

    In this post, we’ll go over the various ways you can upload a video to your WordPress Media Library. Then we’ll walk you through adding a video to a post or page. Finally, we’ll discuss some frequently asked questions related to videos on WordPress. 

    Adding videos to WordPress: The basics

    Before you learn how to add videos to WordPress, it’s helpful to have a basic understanding of what that process means. First off, there’s an important distinction between ‘uploading’ and ‘embedding’ a video into your WordPress site.

    When you add a video directly to WordPress, the video file will be stored on your host’s server. This is called uploading.

    option to upload a video in WordPress

    When you add a video to a post or page in WordPress using a third-party site like YouTube or a video hosting platform like Jetpack VideoPress, this is called embedding.

    trailer for a movie embedded on The Walt Disney Company website

    As you can see in the example above, when you embed a video, you’ll likely get advanced player features. These will be unique to each platform. Sometimes, they’ll include built-in social sharing options to enhance audience engagement.

    Additionally, when you use a third-party host, the video doesn’t actually ‘live’ on your website’s server. Therefore, it won’t have a significant impact on your page loading times. 

    Why should I add a video to WordPress?

    Before we continue, it’s worth discussing some of the many benefits of learning how to upload videos to WordPress. For starters, visual media is on the rise in nearly every virtual space, from ecommerce to social media. As a result, online users have come to expect more video content.

    No matter what type of site you run, videos can help engage your audience and keep them on your site longer. Often, videos are useful to explain complicated concepts or humanize a company or subject. Using videos can also help you meet a wide array of audience preferences and learning styles.

    Tons of creative websites incorporate high-quality video content into their posts and pages. From product videos and promotional content to independent films and lifestyle reels, there are video opportunities for any type of site.

    Can uploading a video slow down your WordPress site?

    When you upload a video directly to your Media Library, it’s saved on the back end of your site and, thus, takes up space on your server. And video files aren’t usually small — adding even just the occasional video can weigh things down and negatively impact performance. 

    This means slower loading times and worse Core Web Vitals scores. This could not only cause your search engine rankings to suffer, but result in frustration for both new and regular site visitors. In other words, if performance tanks as a result of adding a bunch of videos, it could counteract the benefits the videos were supposed to bring in the first place. 

    Luckily, you can avoid all of these adverse effects by simply using a third-party video hosting provider to upload your videos. This way, the clips will use external server resources while still looking great on the front end.

    In this tutorial, we’ll show you how to use various upload methods, so you can ultimately decide which approach is best for your needs.

    How to upload a video to the WordPress Media Library

    Now that you know the basics of adding videos to WordPress, we’re going to go over three methods of doing so.

    Method 1: Using the video hosting plugin Jetpack VideoPress

    With WordPress, the simplest way to upload a video is using a plugin. A video hosting plugin can function similarly to popular options like YouTube and Vimeo.

    But, unlike the alternatives, Jetpack VideoPress is designed specifically for WordPress.

    VideoPress homepage with the tagline, "The finest video for WordPress"

    Using Jetpack VideoPress is highly straightforward because it fully integrates with your WordPress dashboard. It’s also affordable, offering your first video for free and a generous 50 percent discount for your first year.

    Plus, you’ll never have to worry about advertisements interrupting your videos. You’ll even be able to apply your branding to your video player.

    To get started, navigate to your WordPress dashboard. Go to Plugins → Add New. Use the search function to find the Jetpack VideoPress plugin.

    installing Jetpack VideoPress

    After you’ve installed and activated Jetpack VideoPress, you should see the following screen:

    Jetpack VideoPress plan options

    If you like, you can sign up for the premium version of Jetpack VideoPress here. Otherwise, click on Start for free to explore the tool before making a decision.

    After that, you’ll be prompted to connect Jetpack to your site. Click on Approve.

    completing Jetpack setup

    Keep in mind that you won’t need to complete this step if you’ve already connected your website to Jetpack for one of its other tools.

    The connection process should take a few seconds. Then, you’ll be able to add your first video to WordPress.

    option to add your first video

    On the above page, you can either select Add your first video or Select file to upload. Alternatively, simply drag and drop a video onto the page.

    viewing the VideoPress library

    The video will now be added to your Jetpack VideoPress library and your WordPress Media Library. That’s it! Later on, we’ll show you how to insert this video into your posts and pages.

    Method 2: Using your site’s hosting server (not recommended)

    The next way to upload a video in WordPress is by using your site’s hosting server. This method is not recommended because it can slow down your website by consuming a substantial amount of precious server resources. Depending on your hosting provider, they may also have limits on the maximum file size you can upload.

    It’s also not usually the best choice because your playback speed won’t be optimal, and the player will have limited features. In any case, knowing how to carry out this approach can still be useful for certain situations.

    To begin, simply head to your WordPress dashboard. Go to Media → Add New. Then go ahead and drag your video file into the box or click on Select Files.

    uploading new media file to WordPress

    Once the video has finished uploading, your screen will update automatically. It should now have a banner below the Upload New Media section showing your video’s thumbnail.

    media file listed under "upload new media"

    To confirm that your video was uploaded correctly, navigate to Media → Library.

    media library with photos and videos

    You should be able to see your video’s thumbnail in the upper left corner of the screen. 

    At this point, you might notice that your video is mixed with all of your images and other media files. That’s because there isn’t a separation of videos and photos in the WordPress Media Library. 

    Method 3: Using an external hosting server

    The final way you can add a video to WordPress is by using an external hosting server like Amazon S3. While this platform offers the power and security needed for large sites, it’s a fairly complicated and expensive option. 

    To use Amazon S3, you must set up and manage your own server — requiring a good degree of development experience or the help of a professional. Furthermore, AWS S3 isn’t natively designed to integrate with WordPress and doesn’t come with a video player feature.

    For all these reasons, WordPress-specific video hosting options like Jetpack VideoPress often make more sense. They integrate seamlessly with the WordPress Media Library and are usually more affordable.

    Learn more about Amazon S3 and video streaming here

    How to add a video to a WordPress post or page (2 ways)

    Now that you know how to upload a video to WordPress, we’ll show you how to insert one into a page or post. We’ll review two ways you can do this using the Block Editor so that you can easily share videos with your audience.

    Method 1: Using the VideoPress block

    Firstly, let’s see how you can easily use the VideoPress block to add a video to a WordPress page or post. 

    Step 1: Add the VideoPress block

    To begin, you’ll need to create the page or post where you’d like to insert your video. Alternatively, you can navigate to a pre-existing page or post and modify it. Once you’re in the Block Editor, simply click on the plus symbol to Add block.

    "add block" option on a blank page

    Next, use the search tool to look for the VideoPress block.

    VideoPress block in the list of available blocks

    When it appears, click on it, and the block will be added to your page.

    VideoPress block on a page

    Another handy way to add any block to a page or post is by using keyboard shortcuts. For instance, you can type in “/videopress” and access the block that way.

    using a keyboard shortcut to add the VideoPress block

    You can either select the block when it appears or simply hit the enter key to add it to the editing interface.

    Step 2: Add your video and customize its settings

    Once your VideoPress block is on the screen, add your video by selecting Upload, Media Library, or Insert from URL.

    We’re going to go with the Media Library for our example since we already uploaded the video earlier in the tutorial. However, you can also drag and drop your video here to add it to VideoPress. Remember, your videos will be stored separately from your server to improve speed, but will still be visible in the WordPress Media Library.

    uploaded video in the Media Library

    Since the VideoPress block deals with videos, you’ll only see that type of media in your library. When you’ve located the clip you want to use, simply click on it and hit Select.

    block options for VideoPress

    After that, your video will appear on your page. As you can see, the VideoPress block gives you access to a variety of settings. You can enable or disable playback controls, turn on and off autoplay, choose to loop the video, and mute it if you’d like.

    You can also select the dropdown menu next to Progress Bar Colors to change the way that the video’s progress bar appears. There are some other options as well, so feel free to play around until you get the look and functionality that you’re going for.

    progress bar options for VideoPress

    Step 3: Publish and preview your video

    When you’ve finished making your changes, click on Publish in the upper-right corner of your page. Now let’s preview what your video will look like on the front end.

    In this example, we left the progress bar colors setting to Match video. This makes the progress bar blend in, while still remaining functional. 

    Your viewers can make additional adjustments to video speed and quality. Plus, they’ll be able to change to full-screen viewing or create a pop-out window to watch while they scroll.

    Method 2: Using the Video block

    Now, let’s explore how to add a video to a post or page using the default Video block that comes with WordPress. Remember, this will store videos on your server and could cause your site to load more slowly.

    To get started, open up the Block Editor and add the Video block. You can locate the block by clicking on the plus symbol or using keyboard shortcuts.

    adding a Video block to WordPress

    Then, choose your preferred method for adding a video to the block. Again, we’ll insert our clip from the Media Library by hitting Select. The video will now be added to the page.

    options for the Video block

    You should notice that the Video block has some of the same settings as the VideoPress block, though it does provide fewer customization options.

    Once you’ve modified your video block’s settings, click on Publish. Now let’s preview it on the front end:

    preview of the Video block

    As you can see, the progress bar and settings are a bit less discreet, and the video is showing at a lower quality.

    Frequently asked questions

    Hopefully, you’re now comfortable with the basics of uploading videos in WordPress. Just in case, though, we’ll cover some frequently asked questions!

    Can self-hosting my video slow down my WordPress site?

    When you upload large video files to your Media Library without using a tool like Jetpack VideoPress, they’ll occupy space on your website’s server. So, this video hosting option can slow down your website, hindering the overall user experience.

    But this won’t be an issue if you use a video hosting tool like Jetpack VideoPress. This is because the heavy files will be hosted on a separate, more robust server.

    What is the best option to upload a video to WordPress? 

    Using Jetpack VideoPress is hands down the best option to upload a video to WordPress. 

    The plugin provides the best experience for viewers because it can handle and maintain the highest-quality video content. Plus, with Jetpack VideoPress, you’ll never have to worry about ads interrupting your content. 

    Additionally, Jetpack VideoPress is very practical for WordPress creators because it fully integrates with the dashboard and the Block Editor. Lastly, with Jetpack VideoPress, there’s minimal impact on site since your content is served using Jetpack’s global Content Delivery Network (CDN).

    Can I use an uploaded video to build a video header?

    Yes, there are a few ways to use an uploaded video as your WordPress header. You can create this effect using the Cover block or a video plugin. 

    For complete instructions on how to do this, check out the complete tutorial on adding a video background to a WordPress page!

    Where can I learn more about Jetpack VideoPress?

    You can learn more about Jetpack VideoPress on the Jetpack website! Check out the complete list of Jetpack VideoPress features.

    Streamline video uploads in WordPress using Jetpack VideoPress

    Whether you’re an aspiring filmmaker, a talented blogger, or a business owner who understands the value of video, knowing how to add a video in WordPress is key. If you’re not careful, though, your clips can look unprofessional and even slow down your website.

    Fortunately, you can use a video hosting service like Jetpack VideoPress to easily upload videos in WordPress. With Jetpack VideoPress, you can add clips to the Media Library without damaging your site’s performance. Then, you can use the Jetpack VideoPress block to insert your videos into any page or post, with plenty of customization options to improve the viewing experience.

    Are you looking for additional ways to improve your website’s performance? Why not check out Jetpack Complete? This plan offers top-tier performance and security tools for WordPress sites. Plus, it includes Jetpack VideoPress at no additional charge!

  • How to Update Your WordPress Theme (Without Losing Anything)

    Although WordPress themes are typically well-coded, they need regular updates to patch security vulnerabilities and introduce new features. But if you’ve made a lot of customizations to your theme, you might worry that updating it will cause you to lose all of your hard work.

    Fortunately, there are a few easy ways to update your WordPress theme without losing anything. Backing up your site, using a child theme, and testing any changes in a staging environment can help you preserve your settings. Then, you can easily update the theme from your WordPress dashboard, cPanel, or using File Transfer Protocol (FTP).

    In today’s guide, we’ll explore the importance of updating your WordPress theme. Then, we’ll explain the best methods to do this while maintaining any theme customizations. Let’s get to work!

    Why you may need to update your WordPress theme

    Updating your WordPress theme is an essential task. It can enhance your site’s security, introduce new features, and help things run more smoothly. Let’s start by discussing WordPress security

    Security

    The most important reason to update your theme is for website safety. Updates may include security patches that reduce vulnerabilities on your site. If you stick with the older version, you could expose yourself to threats. Because WordPress themes are often open source, anyone could examine your theme’s code and search for possible weak points. 

    Any known security issues will generally be published in the theme’s support forums and changelogs. Therefore, hackers can use this information to identify problems and break into your site.

    In 2021, critical security vulnerabilities were identified in more than 50 WordPress themes. These vulnerabilities exposed users to various attacks, including Cross-Site Scripting (XSS), Remote Code Execution (RCE), and SQL injections. 

    That’s not to say that WordPress themes are inherently unsafe. Developers continually work on the software to improve and protect it. 

    Keeping your theme up-to-date can go a long way towards securing your site. It’s also important that you download themes from reputable sources, and only choose ones that have a number of positive reviews and are compatible with the latest version of WordPress core. The WordPress.org theme repository, for example, is chock full of excellent, free options that are heavily reviewed against WordPress’ coding best practices.

    New features

    From a design perspective, updating your theme can unlock new settings and built-in configuration options. For example, an update might include new blocks or block patterns that you can use across your site. 

    Taking advantage of built-in features means you won’t need to rely as much on third-party plugins and custom CSS. So, you can design the site you want with less time and expense.

    Compatibility

    Finally, themes are often updated for compatibility with WordPress core. Since new versions of core are typically released two or three times a year, theme developers will test their themes against WordPress and update them accordingly.

    This ensures that the software won’t cause bugs, slow down your site, or even break some features. As such, keeping your theme up to date is essential if you want your website to perform at its best. 

    What to do before updating your WordPress theme

    If done incorrectly, updating your theme can mean losing hours of hard work and design customizations. Fortunately, there are some precautionary steps you can take to safeguard your edits. 

    Back up your site

    Backing up your website is a general best practice. If something goes wrong during an update (or any other time), you can simply restore an older version of your site while you troubleshoot and resolve the issue. 

    Fortunately, it’s very easy to create copies of your site with Jetpack VaultPress Backup.

    Jetpack VaultPress Backup homepage with the tagline, "The best real-time WordPress backup plugin"

    Jetpack VaultPress Backup works in real-time, saving every change you make as it happens. The backup is stored off-site, so even if your site goes completely down, you can access and restore it right away. 

    Plus, Jetpack has a WordPress activity log that tracks every action taken, so you can quickly identify the point to which you want to restore.  

    To restore your WordPress website to an earlier version, simply navigate to Jetpack → Backup in your WordPress.com account. Then, you can click through the different days and select Restore to this point for the backup you’d like to use.

    restoring a backup with Jetpack VaultPress Backup

    Or, you can choose an event in your activity log — like a theme update — and restore to just before that occurred.

    restoring a backup from just before an action took place

    Make sure theme customizations are in a child theme

    If you want to edit and customize your WordPress theme, you’ll need to create a WordPress child theme first. The “child” inherits the configuration files, templates, and stylesheets of its “parent,” but WordPress will treat it as an independent theme.

    Any changes you make to the child won’t affect the parent. Plus, updating the parent theme will apply security patches and other upgrades to the child without overriding any custom code you’ve added. 

    If you’re not already working with a child theme, it’s worth making one now. You’ll first want to create a complete backup of your WordPress site

    Then, access your website via File Transfer Protocol (FTP) and head to the root directory (typically called public_html, public, or www). Open wp-content/themes and create a new folder for your child theme. Consider naming it after the parent theme, with “-child” at the end.

    creating a child theme folder

    Inside the folder, create a new text file and name it “style.css”. Next, add the following code to it, updating the information where relevant:

    /*
    
    Theme Name: The name of your theme goes here
    
    Theme URI: http://example.com/twenty-twenty-two-child/
    
    Description: The description of the child theme goes here
    
    Author: John Doe
    
    Author URI: http://example.com
    
    Template: twentytwentytwo
    
    Version: 1.0.0
    
    */

    When you’re ready, save and close the file. Then, create a new file and name it “functions.php”. Add this enqueuing script to it so that WordPress knows how to load the stylesheets in your child theme:

    <?php
    
    add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );
    
    function enqueue_parent_styles() {
    
    wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
    
    }
    
    ?>

    Finally, head to Appearance → Themes in your WordPress dashboard. Find your child theme and click on Activate. It’s now ready for you to use and customize. 

    Consider testing theme changes on a staging site

    A staging website is a copy of your site where you can safely test changes. Any edits you make to the staging environment won’t affect your live website. Then, once you’ve determined that it’s safe to proceed, you can ‘push’ any changes online, where they’ll be visible to anyone who visits your site. 

    Using a staging site is a practical choice from a User Experience (UX) point of view. Playing around with your website while it’s online can cause inconvenience and confuse visitors who may not be able to access particular features. 

    Additionally, utilizing a staging site can show you if a theme update will cause problems. Then, you can avoid pushing the changes live until you have a solution. 

    When running your tests in a staging environment, it’s worth following these steps:

    1. Check for theme compatibility. First, you’ll want to ensure that the theme update has been tested with the version of WordPress you’re running on your site. You may also need to update WordPress core first if you’re using an older version. 
    2. Put Jetpack into “safe mode.” If you’re using the Jetpack plugin, this helps ensure that your connection isn’t broken when setting up a staging site.
    3. Update the theme. You can check out the methods outlined later in this guide to see how to do this. 
    4. Test the site’s functionality. This is the most important part of the process. Consider testing your site’s menus, other navigational elements, forms, and online store. You can also scan your website for visual problems by viewing your posts, pages, and custom post types. 
    5. Verify issues in support forums. If you run into any problems, head to the official WordPress support forums for the theme. There might be known issues that developers are working to resolve. 
    6. Report problems to the theme developer. If no one else has the same issue, it’s a good idea to contact the theme developer. This way, they can fix it for you and all other users. 
    7. Push your changes live. Finally, if everything is looking good, it’s time to push the update live.

    Don’t worry if you don’t already have a staging environment in place. Let’s look at a few easy ways to create one:

    Create a staging site with your web host

    Depending on which WordPress hosting provider you choose, you may have access to a free or paid staging environment. 

    For instance, Bluehost offers staging functionality within your WordPress dashboard. If you have the host’s plugin enabled, head to Bluehost → Staging.

    staging options with the Bluehost plugin

    Now, select Create Staging Site.

    blue button with the words, "Create staging site."

    Bluehost will take a few minutes to create a staging website. It will be a complete copy of your existing site, but any changes you make won’t affect your live page. 

    You can access your staging site by clicking on the circle to the left of its name.

    URL of the new staging site

    Then, you can apply any edits to your live site by hitting Deploy All Changes on the right-hand side. 

    Make a staging site with a plugin

    The Jetpack plugin also enables you to make a staging environment. You’ll simply need to clone your site, import it into a local environment or subdomain, and then work on the website there. This documentation can walk you through the entire process. 

    Alternatively, you could opt for a staging plugin like WP Staging. This free plugin helps you clone your website and work on it safely.

    WP Staging plugin hero image

    Once you’ve installed and activated the plugin in your WordPress dashboard, head to WP Staging → Staging Sites → Create New Staging Site.

    WP Staging step 1, with the option to create a new staging site

    You can then select specific database tables and files or just click on Start Cloning to copy your entire site.

    Step 2, with options for choosing files and database tables

    WP Staging will take a few minutes to clone your website and create a staging environment. Then, it’s ready to go!

    How to update your theme in WordPress (3 methods)

    Now let’s get into the main part of this tutorial. Before running any updates, you should consider the best time of day for this process. 

    Although a theme update takes just a few moments, it could cause temporary glitches on your site that inconvenience visitors. Additionally, if a new software version causes major problems, you don’t want to be scrambling to fix them during an influx of traffic.

    Your first instinct might be to run a theme update in the middle of the night. But, this may not be the best approach if most of your visitors come from a different time zone. 

    You may want to consider using Google Analytics to see when most users come to your site. Then, simply run your theme updates during a quiet period. 

    1. Update your theme using the admin dashboard

    Updating a theme via the WordPress admin dashboard is a very straightforward process. Simply head to Dashboard → Updates and scroll down to the Themes section.

    list of themes with available updates

    Here, tick the checkbox next to your theme and click on Update Themes. The process should complete in a couple of seconds.

    Alternatively, you can find available theme updates under Appearance → Themes. Any outdated themes will have a banner message:

    updates available for three themes

    Simply click on Update now above the applicable theme, and wait a few moments for WordPress to run the update. 

    If, for any reason, this method doesn’t work, there is another option you can take from within the WordPress dashboard:

    1. Go to Appearance → Themes → Add New.
    2. Upload the zip file of the latest version of your current theme. For example, you can update the Twenty Twenty-Two theme by uploading a new copy downloaded from WordPress.org.
    3. Click Replace active with uploaded when prompted.

    2. Update your theme manually via FTP

    Sometimes, you may be unable to update your premium or custom theme from the WordPress dashboard. For instance, if you purchased a theme from outside the WordPress theme repository, it might not add its updates to your dashboard. Fortunately, you can use an FTP client to run the updates.

    Firstly, you’ll need to download the latest version of the theme onto your computer. It should download as a .zip file, so you’ll also have to extract it.

    Next, connect to your website using an FTP client. If you don’t have one installed, FileZilla is a free and user-friendly option. It will ask you for your FTP credentials, so make sure to have them handy, too. 

    Then, head to wp-content → themes.

    selecting the Themes folder

    You may want to download a copy of the existing folder for your theme in case something goes wrong. Then, simply replace it with the unzipped folder you just downloaded. This will override the existing theme files, applying the updates to the theme. 

    3. Update your theme using cPanel

    If your hosting provider uses cPanel, you can also use this application to change your WordPress theme or update it. Again, you may need to use this method if you’ve purchased a premium theme that doesn’t add its updates to the WordPress dashboard.

    Like the previous method, you’ll need to download the latest theme version and unzip the files. Then, log into your hosting dashboard and locate cPanel. You’ll then need to open File Manager.

    selecting the File Manager option

    Now, go to public_html → wp_content → themes. 

    Themes folder inside of wp-content

    Inside, you should see a folder for the theme you want to update. Right-click on it and select Compress to download it as a .zip file to your computer. This way, you’ll have a functional version to restore if you make a mistake.

    Compress option for a folder

    Delete the theme folder and upload the downloaded folder containing the updated theme. When you navigate back to your WordPress dashboard, your site should now be running the latest version of the theme. 

    How to undo a WordPress theme update

    Rolling back or undoing a theme update will revert it to the previous software version. You might need to do this if the updated theme causes problems on your website. 

    If you have a working backup of your WordPress website, you can simply restore it to this version. With Jetpack VaultPress Backup, you’ll just have to open your site with WordPress.com and navigate to Jetpack → Backup

    Then, find a copy of your site that has the older version of the theme, and click on Restore to this point.

    If you don’t have a website backup, a plugin like WP Rollback can help you out. Install and activate the plugin, then head to Appearance → Themes. Click on the theme to see its details, and select Rollback in the bottom-right corner.

    option to roll back a WordPress theme

    You can now choose which version of the theme you’d like to reinstate.

    WP Rollback options

    Click on the circle next to the software version, then select Rollback. The plugin will take care of the rest. 

    Keep in mind that this plugin only works for themes downloaded from the WordPress.org theme Repository. If you have a premium theme and didn’t back up your site, your only option is to manually roll back the update.

    In this scenario, you’ll need to download the previous version of your theme as a .zip folder and unzip the files. Then, connect to your site via FTP or File Manager to replace the current theme folder with the older one. We covered this method in the previous section of the article. 

    Frequently asked questions about updating your WordPress theme

    By now, you should have a good idea of how to update your WordPress theme. If you still have questions about the process, we’ll answer them in this section. 

    Why should you update a WordPress theme?

    Updating a WordPress theme can secure your site by patching over security vulnerabilities within the code. Additionally, theme updates may contain new features or settings that give you more control over your theme’s appearance. 

    Finally, since WordPress core is also updated frequently, new theme versions ensure compatibility with the core software. 

    What happens when you update a WordPress theme?

    Updating a theme involves installing the latest software version. The old theme files will be replaced with new ones during this process.

    Any minor adjustments you’ve made within the theme’s built-in settings should carry over with the update, but custom code will be deleted and lost. For this reason, it’s advisable to back up your theme and make custom edits within a child theme before running any updates. 

    Can I set my WordPress theme to update automatically?

    You can set up automatic updates for your WordPress theme. This setting will save you time since you won’t have to manually upgrade the software. Moreover, you’ll immediately have access to security patches and other benefits. 

    As always, you’ll want to make sure that you’re also backing up your site if you enable automatic updates. Then, you’ll have a functional version of your website on hand if the new software causes problems. 

    In your WordPress admin dashboard, navigate to Appearance → Themes and click on the theme you want to automatically update. Now, select Enable auto-updates from the side menu.

    option to enable auto-updates for themes

    Depending on your host, you may also have theme updates enabled by default. Many hosting providers will automatically update software to save you time and energy. You can then manage these settings from your hosting dashboard.

    turning on automatic theme updates within Bluehost

    In many cases, you’ll just need to toggle a setting to enable and disable automatic theme updates. 

    What if a WordPress theme update gets stuck?

    Occasionally, a WordPress theme update can get “stuck.” This means it will keep trying to update but times out before completing the process. It may even break your site during the process. 

    The easiest solution here is to restore a backup of your WordPress site and then run the update again. If the update continues to get stuck, there are a few simple fixes.

    For starters, consider clearing your browser and server-side caches. There might be files interfering with the update process. Then, reload the page and try running the update again to see if it works.

    The update could also be timing out due to a lack of resources. This is common if you’re using a shared hosting plan. In this scenario, make sure you’re only running one update at a time (rather than multiple themes and plugins simultaneously). 

    The update may also be stuck because it’s only partially complete. In this scenario, you can access your website via FTP, delete the theme folder, and replace it with a downloaded folder from WordPress or the marketplace where you bought the theme. We explained this process in-depth earlier in the post. 

    Update your WordPress theme today

    WordPress theme updates can introduce security fixes, new features, and advanced functionality to your website. Unfortunately, updates can also override custom edits you’ve made or cause problems on your site. 

    Therefore, you’ll want to save a backup and create a child theme before upgrading a theme. It’s also worth testing any changes in a staging environment before pushing them live. Then, updating your theme is simply a matter of clicking a few buttons in your WordPress admin area, accessing your website via FTP, or using cPanel in your hosting dashboard.

    Before updating your WordPress theme, you’ll need to make sure that you have a functional backup in place. With Jetpack VaultPress Backup, you can save copies of your entire website and restore them in seconds. Learn more about Jetpack VaultPress Backup today!

  • How to Fix Cumulative Layout Shift (CLS) on WordPress

    Search engine optimization (SEO) is an ever-changing game without an instruction manual. There’s much more to optimization than just adding keywords into your content. Search engines like Google also take into account indicators of a quality, safe web experience — like how fast your site loads, how easy it is for visitors to interact with it, and more. 

    Cumulative Layout Shift (CLS) is a metric used by Google to measure how much a web page rearranges as it loads. A site that moves significantly — causing users to click the wrong link or have trouble reading content — provides a bad user experience and is frowned upon by Google. 

    Reviewing your site’s CLS score and other Core Web Vitals can help you identify ways to improve its overall health and, in turn, boost your rankings!

    This article will explain the causes of CLS, why you should minimize it, and some methods to reduce it. 

    What is cumulative layout shift?

    Cumulative Layout Shift (CLS) measures the severity of movement on a web page as assets load. You’ve probably noticed that sometimes when you open a website, images and videos can appear at different times and push around other content as they load.

    Here you can see CLS in action:

    images not loading on the GameStop website, a good example of CLS in action

    Bad CLS scores, especially paired with long load times, can be frustrating for visitors. Few things are more aggravating than accidentally clicking an ad because the page suddenly moved underneath your cursor. 

    How does CLS impact user experience on a WordPress site?

    Shifting can be annoying when navigating a web page. It can cause text to jump around as you’re trying to read, buttons to move as you go to click on them, and accidental clicks on ads or links when you want to interact with something else. 

    If visitors have to wait several seconds for a page to fully load and fight with shifting elements, they might simply leave your site. This is especially true if all of your pages shift severely. Visitors are likely to bounce after a few misclicks or excessive wait times. 

    What affects your CLS score?

    A poor CLS score results from major site elements causing other parts of the page to shift as they load. The worst culprits tend to be photos, videos, and ads because these things often load more slowly than text and may have to adjust based on screen sizes. 

    And while decreasing load times can improve your overall UX, this won’t actually reduce the amount of shifting, just mitigate the effects.

    Here are four factors that can affect your CLS score:

    1. Images and videos without size attributes

    Without preset size attributes, visual content like images and videos will often load in smaller placeholders. This means that content around the placeholder will initially take up the ample available space afforded by the small placeholder. Then, when the image arrives, it takes up more space and shifts around neighboring elements. 

    By setting size attributes, the placeholder takes up the same space as the element. So, it loads in the same area and doesn’t affect the placement of nearby content. 

    In the following picture, you can see some early elements loading on the GameStop homepage:

    blank page on the GameStop website

    The images load a few seconds later, pushing the Top Sellers heading down and out of sight. This is a prime example, with fast-loading text being moved around when slow-loading images populate without preset boundaries.

    fully-loaded hompage of GameStop

    This scenario is precisely what you’ll want to avoid or minimize on your site. 

    2. Ads and embeds without size attributes

    If you sell or display ads on your website, they’re likely in image or video format. Like in the example above, if these ads load without size attributes, they probably hit the page later than other content and shift things around. 

    This is especially true for some third-party services that choose advertisements for you. These ads may not always be the same size or fit in the same space. 

    A small graphic might not be a problem. But if a large video ad loads slowly and takes up a lot of space, it could force other elements on your page to move dramatically. 

    Optimizing ads and embedded content to load quickly can reduce the annoyance, though your CLS score will still suffer. Layout shifts that cause visitors to click on your site’s ads inadvertently may leave them feeling tricked and hurt their chances of returning. 

    3. Custom fonts 

    Custom fonts have to be hosted somewhere — like your web server, for example. You’re unlikely to see the Didot font offline (unless you find an old French book). This font offers a formal, elegant feel and is an excellent option for upscale restaurants or antique-related websites.

    Didot font showing a variety of letters

    But since this font is being pulled from somewhere other than the browser, it needs to be downloaded each time a visitor accesses the site. This setup may prevent text from appearing until the font is downloaded. Then, the font can suddenly appear, likely jumbling up any assets already loaded on the page. 

    Another option is to load all the text in a more basic font, like Serif. Then it will be replaced with Didot once it loads in the browser. Since the letters of different fonts don’t usually take up the same amount of space, the font change will shift the text around, pushing or pulling neighboring elements in the process.

    These shifts will increase a CLS score, so it’s in your best interest to avoid them. Luckily, some workarounds allow you to still use custom fonts while solving load time delays. We’ll take a closer look at these methods later in the post. 

    4. Dynamically-injected content

    Dynamically-injected content is a web page element that can change based on certain factors. Often these factors depend on the user, allowing for a more personalized experience.

    For example, an online store may suggest products based on a visitor’s history. A weather website might use the location data of a user’s device to display results for that area.

    Dynamic content can increase conversions with a more relevant experience and product offers. Still, its reactionary nature can be resource-taxing and lead to layout shifts. 

    As in the weather example above, different weather information, the name of the city, or even the language used will take up varying amounts of space on the page. A town with sunny skies and mild weather might be a much simpler entry than a city in the crosshairs of a coming hurricane. 

    The result is that less content will load in the former example, and more will load in the latter, affecting how neighboring elements are shifted on screen. As with any dynamically-injected content that can vary in size or quantity, this will impact the CLS of the page. 

    How to reduce Cumulative Layout Shift on WordPress

    Now that you know the primary contributors to layout shifts on WordPress, you can work towards reducing their impact. 

    As with any time you make fundamental changes to your website, it’s wise to create a backup and use a staging site to catch problems before they go live. 

    Below, you’ll find solutions to reduce CLS and improve your site’s user experience.

    1. Set dimensions for images and videos

    When using images and videos alongside other elements on a page, consider assigning them width and height attributes. These settings will reserve the graphics’ required space and avoid shifting. 

    Fortunately, setting dimensions is very easy in WordPress. Simply click on your embedded image and adjust the Image dimensions to the appropriate values:

    setting dimensions for an image in WordPress

    You can also use aspect ratio boxes to allocate the space for visual elements with CSS before they load. These boxes will have the same effect as set dimensions, reducing layout shifts by pre-assigning the space for images and videos. 

    2. Set dimensions for ads and embedded content

    Like in the step above, you should consider creating space for ads and other embedded content that can cause page shifts. You can do this by setting dimensions for these elements or using CSS to allocate space.

    When ads are populated by third parties, their dimensions can be challenging to predict. So, you can try to estimate an amount of space to set aside and box it out so other content won’t overlap as the ad loads. 

    This setup may result in extra white space around smaller ads. Still, that’s usually better than large ads (that often take longer to load) dramatically moving other elements on your page.

    3. Use fallback fonts to reduce layout shifts

    Earlier, we discussed custom fonts and how they can cause shifting. One possible solution here is to use the ‘font-display’ attribute to match fallback fonts as closely as possible. 

    Browsers load fallback fonts when the custom fonts defined on your site aren’t immediately available. So, while your custom font loads, it will display the fallback fonts that you set. If you match these as closely as you can, the text won’t shift as much when the custom option does load.

    The Font Style Matcher app can be very helpful here. You can select your custom font and fallback font, then preview them on top of one another and make style adjustments as needed. You can even check the box next to “See layout shift due to FOUC” and it will show you how much the page will shift as the font loads.

    comparing two fonts on top of one another

    4. Set placeholders for dynamically-injected content

    Dynamically-injected content can be a helpful feature, but you must implement it strategically to avoid causing layout shifts. The key is to allocate enough space to fit the largest version of the injected content without spilling over and shifting neighboring elements around. 

    You can simplify this process by making all the injected content the same size or as similar as possible. This setup can prevent different results requiring different amounts of space on the page. 

    The actual method for allocating space will depend on the content and approach for injecting it. But it usually requires adding a fixed position and preset boundaries for the assets being loaded.

    How can I measure my WordPress site’s CLS score?

    Since CLS is a significant part of your website’s Core Web Vitals, most site health reports or monitoring tools will highlight it. Below are some of the best options for checking out your site’s CLS score:

    1. PageSpeed Insights

    PageSpeed Insights is a simple resource that provides a report on Core Web Vitals. Simply type in a URL and it will analyze several components, score them, and offer tips for improvements.

    PageSpeed Insights reports, including CLS score

    PageSpeed Insights can run the report for mobile and desktop devices so that you can identify weaknesses on your website for all kinds of visitors. You can also view a treemap for a detailed visual breakdown of performance issues on your site. 

    2. Google Search Console

    Google Search Console is a report generator from Google focused on your site’s health as it pertains to search results. Like with PageSpeed Insights, you can view reports for your site’s mobile and desktop versions with metrics like FID, LCP, and CLS. 

    To use Google Search Console, you’ll first need to verify ownership of your domain. Then, the report will flag poorly-performing aspects of your site, allowing you to pinpoint and solve them.

    3. Lighthouse

    Another Google tool for assessing page quality is Lighthouse — and it’s easy to use for anyone using the Google Chrome browser. It monitors websites in real-time for accessibility, performance, SEO, and more. 

    You can find Lighthouse by going to your Google Chrome browser settings, hovering over More tools, and selecting Developer tools at the bottom.

    Then, you’ll need to expand the menu at the top and choose Lighthouse. From there, you can run the report for the page you’re currently viewing.

    Just select the options you want and click on the Generate Report button.

    CLS report for the GameStop site

    You’ll see color-coded scores at the top for each of the primary metrics. Then, click on each one and scroll down to see a detailed analysis and opportunities for improvement. 

    How can I easily optimize my CLS score right now?

    Using the tools and tips above, you can identify weak points in your Core Web Vitals, including CLS. Once you start fixing some of these issues, your site health will improve, and you can learn how to avoid similar problems in the future. 

    Utilizing these solutions will ensure your CLS score remains in good standing, improving your site’s SEO and UX. You can also use the reports to target other Web Vitals scores like LCP and FID until everything comes back green!

    Other ways to improve Core Web Vitals in WordPress

    With Jetpack Boost, you can monitor and improve your Core Web Vitals and other performance metrics directly from your WordPress dashboard.

    settings for Jetpack Boost

    It scans your website and returns a performance report with areas for improvement. But it goes beyond recommendations with one-click solutions for common issues that can slow down your site and hurt your user experience. 

    How to get started with Jetpack Boost

    To get started, simply install Jetpack Boost from the WordPress Plugins page (it’s free).

    Jetpack Boost in the WordPress plugin repository

    Once the tool is activated, select Boost from the Jetpack tab on the left-hand side of your dashboard.

    You’ll now see a performance score for your site on mobile and desktop devices.

    Jetpack Boost performance scores

    Further down the page, you can turn on additional performance optimization settings, such as CSS loading, deferring non-essential JavaScript, and lazy image loading. Each of these configurations can improve your Core Web Vitals scores. 

    Frequently asked questions 

    Below are some frequently asked questions and answers about CLS on WordPress that may be useful as you dive in.

    What is a good CLS score?

    Anything below 0.1 is considered a good CLS score.

    This number is the difference between the original loading site and the final placement of an element. The score is cumulative, meaning it uses multiple instances from different elements.

    Scores between 0.1 and 0.25 are considered okay and need improvement. Any scores above 0.25 are poor. They suggest that CLS is negatively impacting the usability of your site.

    What if a layout shift is unavoidable?

    Sometimes, a small layout shift may be difficult to avoid due to a lack of knowledge or simply the nature of an element on your page. Don’t worry!

    A few layout shifts here and there shouldn’t significantly impact your site. After all, CLS is a rating compiled from the entirety of the page. Even if your score isn’t a flat zero, a few minor instances can still give you a good overall rating.

    Shifts may simply not be possible to solve on some pages. Again, a minor blemish on your site’s overall UX shouldn’t be a major cause for concern. 

    Do user interactions affect Cumulative Layout Shift?

    No! Browsers calculate CLS, and they should explicitly ignore user-driven shifts. Requiring a user action before loading variable content can actually be a helpful trick to help avoid CLS in some situations. 

    For instance, say you use dynamically-injected content to load a map of nearby stores for visitors. If this happens automatically, the time to pull the user’s location data and load the map could cause a layout shift. But if there’s a button that the user must click to load the map, this interaction will prevent the layout shifts from affecting the page’s CLS score. 

    Improve Cumulative Layout Shift on WordPress

    Now that you know how to fix Cumulative Layout Shift (CLS) on WordPress and how to measure it, you can improve your website’s SEO and UX. Reducing shifts will make navigating your website more pleasant for visitors and should also boost your rankings on the search engine results pages. 

    To minimize your CLS score, remember to:

    1. Set dimensions for images, videos, ads, and other embedded content.
    2. Reduce shifts in fonts upon loading
    3. Set placeholders for dynamically-injected content.

    While Cumulative Layout Shift is just one factor that affects your site’s SEO, it’s also a noticeable UX consideration. A little work can have lasting improvements in your search rankings and the visitor’s experience once they arrive. 

  • How to Defer Parsing of JavaScript in WordPress

    JavaScript is one of the most popular programming languages in the world. Most websites use it to create more dynamic experiences for visitors. Critical features like contact forms and site analytics are just a couple of ways JavaScript is put into practice on a daily basis. Unfortunately, while it’s highly useful, all of this code has the potential to slow down your site. 

    Deferring parsing of JavaScript (also just called, “deferring JavaScript”) means telling your site to load your non-essential JavaScript code last. This simple tweak can improve your page loading times and overall performance, depending on the number of scripts your website uses.

    In this article, we’ll break down exactly what parsing is and what deferring involves. We’ll also discuss how deferring JavaScript can benefit your site and show you how to do it. Finally, we’ll wrap up with some frequently asked questions (FAQs) to address any remaining doubts. 

    What does “defer parsing of JavaScript” mean?

    When you visit a website, your browser requests files from a server. These files contain HTML, CSS, and JavaScript for the browser to parse (interpret) in order to create a visual and interactive web page.

    Websites often require your browser to load dozens (or even hundreds) of elements and files for just a single page. Here’s a quick example from one of Google’s pages, so you can see how many files it uses:

    list of files from Google from the Network tab of Google Developer Tools

    When your browser parses HTML files, it stops to render any CSS that it finds and to execute JavaScript code. Until the browser has finished executing that code, it won’t continue to load the rest of the page.

    In practice, you might not notice this delay if your website is very well optimized (if it loads really quickly). But the delay is there, and the more JavaScript your site uses, the longer it can be. If your website isn’t optimized for performance, parsing of JavaScript can significantly slow down its loading times.

    Deferring the parsing of JavaScript means telling your browser, “Hey, if you run into this JavaScript code, don’t parse it until you’re done with the rest of the page.” From the visitor’s perspective, this means the visible elements of the page will load faster. Then, the JavaScript will finish executing in the background, and no one will be any the wiser (except you and the browser).

    What are the benefits of deferring JavaScript?

    The primary benefit of deferring JavaScript is that pages will load faster for visitors. Scripts will still need to load in the background, but deferring them should improve your Largest Contentful Paint (LCP) score, which is one of three Core Web Vital metrics.

    It’s important to remember that page loading time is one of the most important aspects of a great user experience. If a website takes too long to load, you’ll typically lose a percentage of visitors. Moreover, slow loading times can give the impression that there’s something wrong with your site.

    How to defer parsing of JavaScript in WordPress

    WordPress offers more than one way to optimize your website. When it comes to deferring JavaScript, there are two methods you can use. 

    The first method is the easiest because it involves using a plugin.

    1. Defer JavaScript parsing with a free plugin

    If you’re not comfortable editing your website’s files and adding code to them, your best bet is to use a plugin. One of the best tools you can use to defer non-essential JavaScript in WordPress is Jetpack Boost.

    Jetpack Boost homepage design

    Jetpack Boost is a free plugin you can use to optimize your WordPress site’s performance. It’s incredibly straightforward to configure, making it an excellent choice for beginners. 

    Once you activate the plugin, you’ll need to connect to a WordPress.com account (you can use a free account for this). 

    When you’re ready, go to Jetpack → Boost in your WordPress dashboard, and you’ll get a quick overview of how your website is doing in terms of performance.

    speed test from Jetpack Boost

    If you look at the options below, you’ll see a setting that says Defer Non-Essential JavaScript. You can toggle this setting, and it will automatically defer parsing of JavaScript throughout your website.

    option to defer non-essenntial JavaScript

    The plugin specifies non-essential JavaScript because it only impacts scripts that aren’t critical to the website.

    Once this setting is enabled, be sure to look through your website to ensure that everything is working well. If you notice anything unexpected, simply disable the feature.

    Note that Jetpack Boost can also enable lazy loading and optimize your site’s CSS. This means that the plugin will move critical CSS to the start of each HTML document so that the browser parses it first. This setting is particularly important for improving your First Input Delay (FID) score.

    2. Defer parsing of JavaScript using the functions.php file

    The second method involves editing your theme’s functions.php file. The process is not overly complicated, but adding code to WordPress can sometimes result in unexpected side effects.

    This method is for experienced users, as a lot can happen by deleting just one file or even accidentally adding a space in the wrong place. Remember, you’ll want to only defer non-essential JavaScript to avoid hurting the user experience.

    To be safe, we recommend backing up your website fully before editing any WordPress files. Even if you have a recent backup, create another one so that you have a restore point before making any changes. If you have Jetpack VaultPress Backup, the most recent version of your site will already be saved for you. 

    There are two ways to edit the functions.php file. You can use the WordPress Theme File Editor, which you can access from the Appearance menu. Keep in mind that this option is only available if you’re not using a block theme that supports Full Site Editing (FSE).

    Once you access the editor, select your active theme from the dropdown menu to the right and look for the functions.php file in the list.

    Edit Themes area of WordPress

    You can use the editor to add or remove code from any theme files. Still, we recommend against modifying any existing code unless you understand its purpose.

    Adding code to functions.php should be safe as long as it’s from a trusted source. The following code snippet will configure your website to defer parsing of JavaScript:

    function defer_js( $url ) {
    
        if ( is_user_logged_in() ) return $url; 
    
        if ( FALSE === strpos( $url, '.js' ) ) return $url;
    
        if ( strpos( $url, 'jquery.js' ) ) return $url;
    
        return str_replace( ' src', ' defer src', $url );
    
    }
    
    add_filter( 'script_loader_tag', 'defer_js', 11 );

    This code will automatically defer all JavaScript on your site, but it won’t touch jQuery scripts. However, it won’t work if you’re logged in to avoid issues with the dashboard not loading properly.

    Add that script at the end of the functions.php file so that it doesn’t interfere with any of the other code inside. Click Update File at the bottom of the page, and that’s it!

    If you don’t have access to the WordPress theme file editor but are comfortable working with code on a server, you can edit functions.php by connecting to your website via File Transfer Protocol (FTP). You’ll need to use an FTP client like FileZilla to do this. Remember, be sure you take a full site backup before doing anything.

    Once you connect to your website’s server, you’ll need to find the WordPress root folder. This is the folder that contains all of your site’s files. It’s usually named www, public_html, or your site’s name.

    Open that folder and go to wp-content/themes. There should be several folders, one for each theme installed on your site. Identify your active theme’s folder and open it. The functions.php file should be right inside.

    finding the functions.php file in WordPress

    Right-click on that file and look for an option that says something like Edit (this will vary depending on the FTP client you use). That option will open the file using your default text editor. From here, you can add the code snippet we shared earlier and then save the changes to the file.

    The same rules apply when editing WordPress files via FTP. Don’t edit any code if you’re unsure what it does, and be wary about adding code snippets unless you trust their source.

    You can always restore your WordPress site using the recent backup if you run into errors after editing the functions.php file. Jetpack VaultPress Backup is a fantastic option in these cases because it offers one-click restore functionality even if your site is completely down.

    Frequently asked questions about deferring JavaScript

    If you still have any questions about how deferring JavaScript works, this section will answer them. Let’s start by talking about the potential side effects of deferring scripts.

    Can deferring JavaScript break your site?

    Yes, depending on the plugins and theme you’re using, it’s possible that deferring JavaScript could break certain elements of your site. And, if you’re using the manual method, an error in your code could bring your site down entirely.  

    That’s why it’s safest to use a tool like Jetpack Boost to take care of this task. While it’s still possible that deferring JavaScript could cause an issue, you can easily deactivate the feature or plugin entirely. 

    Is deferring parsing of JavaScript the same as “removing render-blocking JavaScript”?

    If you use website performance measurement services like PageSpeed Insights or GTMetrix, you might notice they also recommend eliminating render-blocking JavaScript from your website. Due to the language, it can be easy to confuse this optimization suggestion with deferring parsing of JavaScript.

    Render-blocking JavaScript refers to any code that blocks your site from rendering. In many cases, the best solution is to eliminate this code if it doesn’t fulfill a specific purpose. If it has a function, you can defer it instead.

    Determining which scripts are needed and which aren’t will depend on your judgment. But services like GTMetrix can help you identify unused JavaScript on your website.

    list of unused JavaScript files on a site

    Any scripts that fall under this category should be safe to remove. For other scripts, you can use either plugins (like Jetpack Boost) or modify the functions.php file manually to defer them.

    Can I safely remove JavaScript instead of deferring it?

    This depends on which scripts you’re referring to. It’s not uncommon for WordPress websites to accumulate unused code as they grow. This happens as you install and deactivate plugins, try out third-party services, and stop using them.

    Leaving that “orphaned” JavaScript on your website can sometimes create a security risk. Moreover, it can impact your website’s performance because browsers might still need to parse it. 

    If you check out the previous question, we show you how to use GTMetrix to identify JavaScript on your website that you can remove safely.

    Does deferring JavaScript improve page performance?

    Deferring JavaScript should make your website’s pages load faster. How much faster will depend on the number of scripts you’re deferring and how well optimized your website is.

    If you already have a fast website, and you’ve taken steps to optimize it, like removing unused scripts, deferring JavaScript might not have a significant impact. Still, every bit of optimization counts when it comes to page performance.

    What else can I do to improve my page loading speeds?

    There are a lot of ways to improve page loading speeds for a website. For the greatest impact, here are the optimizations we suggest implementing:

    1. Consider using a managed WordPress hosting provider.
    2. Implement a Content Delivery Network (CDN).
    3. Improve Core Web Vitals in WordPress.
    4. Minify CSS.
    5. Enable lazy loading in WordPress.

    Optimizing your website for performance can take a while, but WordPress plugins like Jetpack and Jetpack Boost make the process much easier and faster.

    Remember that any effort you make to improve your page loading speeds will more than pay off over time. If you can keep your website running in top shape, your visitors will have a much better experience.

    Improve your website’s performance today

    There are a lot of changes you can make to your website to improve its performance. If you use multiple third-party scripts and plugins on your site, there’s probably a lot of JavaScript code running in the background. That code is important, but it may prevent the rest of your website from loading as fast as possible.

    Deferring parsing of JavaScript in WordPress is easier than you might think and can significantly impact your website’s performance. Here are the ways you can defer JavaScript parsing:

    1. Use a plugin like Jetpack Boost.
    2. Defer JavaScript using the functions.php file.

    Jetpack offers several plugins to improve your WordPress website’s performance. Jetpack Boost is only one of them. If you use the Jetpack plugin, you also get access to a free CDN that can drastically improve your site’s loading speeds. Consider starting with Jetpack today!