Skip to main content
Dublin Library

The Publishing Project

Live Core Web Vitals Measurements In WordPress

 

Building the Core Web Vitals measurement into WordPress is a bit more involved as it depends on whether you've analytics into your site and how you've done it. This function depends on Google's [Sitekit plugin](https://sitekit.withgoogle.com/) and relies on values set there. We can run a function that checks if the `gtag` script has already been enqueued on your site: * If it's hasn't been enqueued, then you add it and configure it * If it's already been enqueued, then do nothing, as it's ready to use If you use a different tool to set up your Google Analytics or use a different analytics solution, you'll need to set it up and configure it yourself. ```php import {getCLS, getFID, getLCP} from "https://unpkg.com/web-vitals?module"; function sendToGoogleAnalytics({name, delta, id}) { gtag("event", name, { event_category: "Web Vitals", event_label: id, value: Math.round(name === "CLS" ? delta * 1000 : delta), non_interaction: true, }); } getCLS(sendToGoogleAnalytics); getFID(sendToGoogleAnalytics); getLCP(sendToGoogleAnalytics); '; } add_action( 'wp_footer', 'web_vitals_init' ); ``` Collecting this data gives you better feedback on how your site is doing and how your users are experiencing the content. Right now I'm adding this to my theme's `functions.php`. I should make a plugin out of it but I want to make sure it works and sends the data I want before I make it into one.

Edit on Github