0 Day Analytics – Performance Module Developer Documentation

Table of Contents

1. Overview & Architecture

The Performance Module provides a three-tab performance analysis dashboard within the WordPress admin. It combines automated site health checking, URL tracking, and Google PageSpeed Insights integration to give administrators a comprehensive view of their site’s performance, security, and SEO posture.

Key Capabilities

  • Site Health — 32 automated checks across Security, Speed, and Resources categories with weighted scoring (0–100)
  • URLs — URL tracking list with per-URL asset collection and PageSpeed analysis
  • Page Speed — Google PageSpeed Insights API v5 integration for mobile and desktop analysis
  • Core Web Vitals metrics: FCP, LCP, TBT, CLS, SI
  • Category scores for Accessibility, Best Practices, SEO, and Performance
  • Audit filtering by Core Web Vital metric type
  • Diagnostic and opportunity identification with expandable detail panels
  • Screenshot and filmstrip rendering from Lighthouse data
  • Chart.js doughnut gauge visualization for scores
  • Dark mode support via aadvana-darkskin CSS class
  • Cached results with configurable refresh
  • Encrypted API key storage at rest

Technology Stack

  • PHP 7.4+ (strict types)
  • Google PageSpeed Insights API v5
  • WordPress REST API for data retrieval
  • Chart.js for gauge and score visualizations
  • wp.template (Underscore.js) for client-side rendering
  • wp-api-fetch and custom makeRestRequest() for REST calls
  • wp-i18n for JavaScript translations
  • WordPress Transient API for caching
  • Secure_Store class for API key encryption at rest

2. File Map

advanced-analytics/
├── classes/
│   └── vendor/
│       ├── lists/
│       │   ├── class-pagespeed-list.php           — PageSpeed API data handler & response normalizer
│       │   ├── views/
│       │   │   ├── class-performance-view.php     — Performance page rendering (3-tab UI, Site Health)
│       │   │   ├── class-urls-view.php            — URLs tab rendering & asset/PageSpeed modals
│       │   │   └── pagespeed-templates.php         — Underscore.js (wp.template) templates
│       │   └── entity/
│       │       └── class-common-table.php         — fetch_pagespeed_for_url(), collect_pagespeed()
│       ├── controllers/
│       │   └── class-endpoints.php                — REST API route registration
│       ├── helpers/
│       │   ├── class-settings.php                 — Plugin settings (pagespeed_api_key, etc.)
│       │   └── class-secure-store.php             — API key encryption/decryption at rest
│       ├── checks/
│       │   ├── class-scanner.php                  — Site health scanner (32 checks)
│       │   └── class-score-calculator.php         — Score calculation for security/speed/resources
│       └── entities/
│           └── class-urls-log-entity.php          — URL record persistence & PageSpeed data storage
├── js/
│   └── admin/
│       ├── pagespeed.js                           — PageSpeed UI logic (1026 lines)
│       ├── util.js                                — REST request helper (makeRestRequest)
│       └── lib/
│           └── chart.js                           — Chart.js library
└── css/
    └── admin/
        └── style.css                              — PageSpeed styles (lines 6539–7100+)

3. Admin Screens & Tabs

URL wp-admin/admin.php?page=advan_performance
Menu Position Sub-menu under “Error Logs” (position 9)
Capability manage_options (or read if menu_admins_only is off)
Controller Performance_View::analytics_performance_page()
Menu Registration Performance_View::menu_add()

The page uses a WordPress nav-tab-wrapper with three tabs, selected via the tab query parameter:

3.1 Site Health Tab

URL wp-admin/admin.php?page=advan_performance&tab=checks
Default Tab Yes (displayed when tab is absent or checks)
Handler Performance_View::render_checks_tab()
Scanner Scanner::run_all()Score_Calculator::calculate()
Cache Transient aadvana_site_checks_data (1 day TTL)

UI Components

  • “Re-run Site Health Checks” button — nonce-protected refresh with advan_refresh_checks
  • Last analysed timestamp — human-readable (“just now”, “5 minutes ago”, etc.)
  • Overall score circle — 0–100 with color grade (good ≥ 80, ok ≥ 50, bad < 50)
  • Chart.js doughnut gauge — pass/warning/info/fail percentage breakdown
  • Category score badges — Security, Speed, Resources (via tmpl-aadvana-pagespeed-category-score)
  • Check results table — per-category (Security, Speed, Resources) with status icon, title, description, result, recommendation

Score Calculation

  • Scanner::run_all() returns results grouped by category: security, speed, resources
  • Each check has a status (pass, warning, info, fail) and optional severity
  • Score_Calculator::calculate() produces: overall, security, speed, resources scores (0–100) plus counts
  • Percentages for the gauge chart are computed as count / total * 100
Session Safety: The scanner is invoked in the load-{page} hook (via ensure_checks_cached()) rather than during page rendering. This prevents loopback HTTP requests from rotating the session token after the REST nonce has been embedded in the page, which would cause 403 errors on subsequent REST calls.
Screen layout:
┌──────────────────────────────────────────────────────────────┐
│  Performance - Site Health                                   │
│──────────────────────────────────────────────────────────────│
│  [Site Health] [URLs] [Page Speed]                           │
│──────────────────────────────────────────────────────────────│
│  Last analysed: 5 minutes ago     [Re-run Site Health Checks]│
│                                                              │
│  ┌─────────┐  Site Health Score                              │
│  │   82    │  28 passed • 3 warnings • 1 failed              │
│  │  /100   │  Security: 90  Speed: 78  Resources: 80         │
│  └─────────┘                                                 │
│                                                              │
│  [Gauge]  [Security: 90] [Speed: 78] [Resources: 80]         │
│                                                              │
│  Security ──────────────────────── 90/100                    │
│  ☐ Status | Check           | Result    | Recommendation     │
│  ✓        | HTTPS enforced  | Active    | —                  │
│  ⚠        | Debug mode      | Enabled   | Disable in prod    │
│                                                              │
│  Speed ────────────────────────── 78/100                     │
│  ...                                                         │
│                                                              │
│  Resources ────────────────────── 80/100                     │
│  ...                                                         │
└──────────────────────────────────────────────────────────────┘

3.2 URLs Tab

URL wp-admin/admin.php?page=advan_performance&tab=urls
Handler Urls_View::render_page()
List Table Urls_List
Settings urls_module_enabled, advana_urls_enable

UI Components

  • URL list table with search and pagination
  • URL detail modal via wp.apiFetch (GET /0-day/v1/get_url_record/{table}/{id}/)
  • Assets collection button (POST /0-day/v1/collect_assets/{id})
  • Per-URL PageSpeed collection (POST /0-day/v1/collect_pagespeed/{id})
  • PageSpeed score badges in list columns (good/average/poor color coding)
  • Warning banner when URL data collection is disabled

3.3 Page Speed Tab

URL wp-admin/admin.php?page=advan_performance&tab=pagespeed
Handler Inline in Performance_View::analytics_performance_page()
API Requirement Google PageSpeed API key in settings (pagespeed_api_key)
Scripts advan-pagespeed-js + advan-chart-js + advan-util-js

UI Components

  • URL input — pre-filled with home_url('/'), accepts any URL
  • “Run PageSpeed Analysis” button — triggers REST API call
  • Loading hint — displayed during analysis (up to 60 seconds)
  • Error banner — shown for URL validation errors or API failures
  • Mobile/Desktop tab switcher — toggles between device result panels
  • Per-device result container:
    • Screenshots area (final screxenshot + filmstrip thumbnails)
    • Performance gauge (Chart.js doughnut with score overlay)
    • Category score badges (Accessibility, Best Practices, SEO)
    • CWV metrics tiles (FCP, LCP, TBT, CLS, SI) with color coding
    • Audit metric filter (All / FCP / LCP / TBT / CLS radio buttons)
    • Opportunities section (expandable accordion)
    • Diagnostics section (expandable accordion)
    • Passed Audits section (expandable accordion)
    • Accessibility / Best Practices / SEO audit sections
API Key Required: When pagespeed_api_key is empty, the tab shows a warning notice with a link to the settings page instead of the analysis UI.
Screen layout:
┌────────────────────────────────────────────────────────────────┐
│  Performance - Page Speed                                      │
│────────────────────────────────────────────────────────────────│
│  [Site Health] [URLs] [Page Speed]                             │
│────────────────────────────────────────────────────────────────│
│  [https://example.com/________] [Run PageSpeed Analysis]       │
│                                                                │
│  ⓘ Analysis started - collecting data from Google PageSpeed...│
│                                                                │
│  [● Mobile] [○ Desktop]                                        │
│                                                                │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐           │
│  │Screenshot│ │  Gauge   │ │Access: 92│ │ SEO: 95  │           │
│  │ [image]  │ │   87     │ │Best P: 88│ │          │           │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘           │
│                                                                │
│  Metrics                                                       │
│  [FCP 1.2s ✓] [LCP 2.1s ▲] [TBT 120ms ✓] [CLS 0.05 ✓]          │
│  [SI 3.1s ▲]                                                   │
│                                                                │
│  Show audits relevant to: (●) All (○) FCP (○) LCP ...          │
│                                                                │
│  ▸ Opportunities ──────────────────────────────                │
│  ▸ Diagnostics ────────────────────────────────                │
│  ▸ Passed Audits ──────────────────────────────                │
│  ▸ Accessibility ──────────────────────────────                │
│  ▸ Best Practices ─────────────────────────────                │
│  ▸ SEO ────────────────────────────────────────                │
└────────────────────────────────────────────────────────────────┘

4. Core Classes

4.1 ADVAN\Lists\Views\Performance_View

Main controller for the Performance page. Handles menu registration, tab routing, Site Health check execution and rendering, and caching logic. All methods are static.

Constants

PHP
<?php
public const MENU_SLUG        = 'advan_performance';
private const CHECKS_TRANSIENT = 'aadvana_site_checks_data';

Public Static Methods

Method Parameters Return Description
menu_add() void Registers the “Performance” submenu under Error Logs at position 9. Adds load-{hook} actions for help tabs, URL list processing, check refresh, and cache priming.
analytics_performance_page() void Main page callback — renders the 3-tab UI (Site Health / URLs / Page Speed). Reads tab query parameter to determine which tab to display. Enqueues Chart.js for the checks tab.
render_checks_tab(string $refresh_url) Nonce-protected refresh URL void Renders the Site Health dashboard: score banner, Chart.js gauge, category badges, and per-category check result tables.
handle_refresh_checks() void Hooked to load-{page}. Handles ?refresh_checks=1 with nonce verification (advan_refresh_checks). Deletes transient, re-runs scanner, and redirects.
ensure_checks_cached() void Hooked to load-{page}. Runs scanner on first visit or after transient expiry (checks tab only). Prevents session-rotation issues.
add_help_content_performance() string Returns help tab content text.

Private Methods

Method Description
run_and_cache_checks() Runs Scanner::run_all(), calculates scores via Score_Calculator::calculate(), computes status percentages, stores everything in the transient (1 day TTL).
score_grade(int $score) Maps 0–100 score to CSS class: 'good' (≥80), 'ok' (≥50), 'bad' (<50).
status_icon(string $status) Returns Unicode character: ✓ (pass), ℹ (info), ⚠ (warning), ✗ (fail).

4.2 ADVAN\Lists\PageSpeed_List

Handles Google PageSpeed Insights API communication, data caching, and response normalization. All methods are static.

Constants

PHP
<?php
public const SCREEN_OPTIONS_SLUG = 'advanced_analytics_pagespeed_list';
public const PAGE_SLUG           = ADVAN_INNER_SLUG . '_page_advan_performance';

Properties

Property Type Description
$wp_screen \WP_Screen Current admin screen (protected, static)

Public Static Methods

Method Parameters Return Description
init() void Calls hooks_init()
hooks_init() void Registers admin_print_styles-{PAGE_SLUG} hook for asset enqueuing
print_styles() void Enqueues advan-pagespeed-js, localizes advanPagespeedSettings and advanPagespeedMessage, registers script translations
get_pagespeed_api_data($request) WP_REST_Request WP_REST_Response REST callback — returns cached data (if cached=true) or fetches fresh data for the given URL
prepare_pagespeed_api_response($response) array (raw API response) array Normalizes Lighthouse response: extracts categories, audits with details, screenshots, filmstrip, and diagnostic type mapping

Private Methods

Method Description
get_cached_pagespeed_data() Reads transient aadvana_cached_pagespeed_api_data
fetch_pagespeed_api_data(string $custom_url) Calls Common_Table::fetch_pagespeed_for_url(), caches result for 1 hour

Localized Script Data

Object Name Properties Description
advanPagespeedSettings url, permalink, nonce REST API base URL, permalink structure, and WP REST nonce
advanPagespeedMessage homeurl Site home URL for default PageSpeed input

4.3 ADVAN\Lists\Views\Urls_View

Renders the URLs tab content including the list table and modals for URL details, assets, and per-URL PageSpeed analysis.

Public Static Methods

Method Description
enqueue_pagespeed_assets() Enqueues media-views CSS, wp-api-fetch, Chart.js, advan-util-js, advan-pagespeed-js
analytics_urls_page() Entry point for the URLs page (internal delegation)
render_page() Renders the URLs tab: list table + URL details modal + PageSpeed modal
render_url_details_modal() Outputs HTML/CSS/JS for URL detail modal with assets collection and PageSpeed buttons
format_value_for_html($value) Formats JSON/serialized values for HTML display

5. Data Flow

PageSpeed Analysis (Standalone Tab)

User clicks "Run PageSpeed Analysis"
  → pagespeed.js: makeRestRequest('pagespeed_api_data/pagespeed_api_data?url=...')
    → REST: GET /0-day/v1/pagespeed_api_data/pagespeed_api_data
      → PageSpeed_List::get_pagespeed_api_data()
        → fetch_pagespeed_api_data()
          → Common_Table::fetch_pagespeed_for_url($url)
            → Google API: pagespeedonline/v5/runPagespeed (MOBILE, 300s timeout)
            → Google API: pagespeedonline/v5/runPagespeed (DESKTOP, 300s timeout)
          → PageSpeed_List::prepare_pagespeed_api_response() × 2
          → set_transient('aadvana_cached_pagespeed_api_data', data, HOUR_IN_SECONDS)
    → pagespeed.js: handleAPIResponse()
      → showPageSpeedData() (mobile) + showPageSpeedData() (desktop)
        → showMetrics() → showGauge() → showDiagnostics()
        → showCategoryScores() → showCategoryAudits() → showScreenshots()

Per-URL PageSpeed Collection (from URLs Tab)

"Run PageSpeed" button in URL list
  → wp.apiFetch: POST /0-day/v1/collect_pagespeed/{id}
    → Common_Table::collect_pagespeed($request)
      → Urls_Log_Entity::load() → get URL string
      → Common_Table::fetch_pagespeed_for_url($url)
      → Urls_Log_Entity::update_pagespeed_data($id, $data)
    → Response: { success: true, data: {...}, errors: [...] }

Site Health Checks

Page load (load-{hook} phase)
  → Performance_View::ensure_checks_cached()
    → Scanner::run_all() → 32 checks across security/speed/resources
    → Score_Calculator::calculate() → overall, security, speed, resources scores
    → set_transient('aadvana_site_checks_data', ..., DAY_IN_SECONDS)

Page render
  → Performance_View::render_checks_tab()
    → get_transient('aadvana_site_checks_data')
    → Render score banner, gauge chart, category tables

Cached Data Auto-Load

Page load (pagespeed tab)
  → pagespeed.js: pageSpeedInit()
    → makeRestRequest('pagespeed_api_data/pagespeed_api_data?cached=1')
    → If cached data exists → handleAPIResponse() renders immediately
    → If no cache → shows empty state, user clicks "Run" button

6. REST API Endpoints

All endpoints are registered under the 0-day/v1 namespace via Endpoints::init_endpoints(). Every endpoint requires manage_options capability.

Fetch PageSpeed Data GET

Route /0-day/v1/pagespeed_api_data/pagespeed_api_data
Method GET
Handler PageSpeed_List::get_pagespeed_api_data()
Parameters
  • url (string, optional) — URL to analyze; defaults to home_url()
  • cached (bool, optional) — if truthy, return cached results only
Response { data: { mobile_data: {...}, desktop_data: {...}, url: "..." }, success: true, message: "" }
Error Cases data: false when no API key is configured or API returns error

Collect PageSpeed for URL POST

Route /0-day/v1/collect_pagespeed/(?P<id>\d+)
Method POST
Handler Common_Table::collect_pagespeed()
Parameters id (integer, required) — URL record ID from the URLs tracking table
Response { success: true, data: {...}, errors: [...] }
Side Effects Persists results via Urls_Log_Entity::update_pagespeed_data($id, $data)

7. JavaScript Architecture

js/admin/pagespeed.js (1026 lines)

Main PageSpeed UI script. Dependencies: wp-util, wp-i18n, advan-chart-js, advan-util-js.

Key Functions

Function Description
pageSpeedInit() Entry point — loads cached data, binds “Run” button, sets up accordion/filter/device-tab event handlers
handleAPIResponse(response) Processes server response; renders mobile + desktop data or error banners. Exposed globally as window.handleAPIResponse
showPageSpeedData(data) Renders one device’s Lighthouse data: skeleton → metrics → diagnostics → category scores → screenshots
showMetrics(metrics, performanceScore) Renders CWV metric tiles (FCP, LCP, TBT, CLS, SI) via tmpl-aadvana-pagespeed-metrics
showGauge(scores, performanceScore) Renders Chart.js doughnut gauge with weighted category scores
showDiagnostics(diagnostics) Splits audits into Opportunities, Diagnostics, and Passed; renders accordion items
showCategoryScores(categories) Renders score badges for accessibility, best-practices, SEO
showCategoryAudits(catKey, catLabel, audits) Renders accordion items for non-performance category audits
showScreenshots(screenshots) Renders final screenshot + filmstrip thumbnails with timing labels
renderAuditDetails(auditId, details) Renders table/list detail panels inside audit accordion rows
escHTML(str) / escAttr(str) HTML and attribute escaping helpers
formatMs(ms) / formatBytes(bytes) Human-readable millisecond and byte formatting

Metric Filter System

Per-device radio buttons filter audit accordion items by CWV metric type. Each audit carries a data-metric-type attribute (set from the diagnostics mapping in prepare_pagespeed_api_response()). Selecting a filter hides non-matching audits.

js/admin/util.js (51 lines)

Generic REST helper: makeRestRequest(endpoint, data, method) — uses fetch() with X-WP-Nonce header from advanPagespeedSettings.nonce.

8. Underscore.js Templates

Templates defined in pagespeed-templates.php using WordPress wp.template (Underscore.js syntax). Included by Performance_View::analytics_performance_page().

Template ID Data Context Description
tmpl-aadvana-pagespeed-device data = device name Device container skeleton: screenshots area, gauge canvas, metrics, metric filters, opportunities/diagnostics/passed audit sections, accessibility/best-practices/SEO sections
tmpl-aadvana-pagespeed-metrics data.title, data.value, data.scoreClass Single CWV metric tile with color coding (fail/average/pass)
tmpl-aadvana-pagespeed-diagnostics data.id, data.title, data.score, data.description Single audit accordion row with score icon and expandable detail panel
tmpl-aadvana-pagespeed-gauge data.overallPerformance Performance score number overlay centered on the doughnut chart canvas
tmpl-aadvana-pagespeed-category-score data.title, data.scoreInt, data.device Category score circle badge (pass=green, average=orange, fail=red)
tmpl-aadvana-pagespeed-screenshot data.src Final screenshot image element
tmpl-aadvana-pagespeed-filmstrip data.src, data.timing Page-load filmstrip thumbnail with timing label

9. Hooks & Actions

WordPress Hooks Registered ACTION

Hook Callback Priority Description
admin_print_styles-{PAGE_SLUG} PageSpeed_List::print_styles() default Enqueues PageSpeed JS, CSS, and localized data
load-{performance_hook} Settings::aadvana_common_help() default Adds common help tabs to the page
load-{performance_hook} Urls_List::process_actions_load() default Processes URL list actions before output
load-{performance_hook} Performance_View::handle_refresh_checks() default Handles site health check refresh with nonce verification
load-{performance_hook} Performance_View::ensure_checks_cached() default Primes the checks transient on first visit
rest_api_init Endpoints::init_endpoints() default Registers all REST routes including PageSpeed endpoints

10. Settings Reference

Settings are managed via the Performance tab in the plugin settings page (admin.php?page=advan_logs_settings#aadvana-options-tab-performance).

Setting ID Type Description
Enable performance module performance_module_enabled checkbox Master toggle for the Performance module. When disabled, the sub-menu is hidden.
Google PageSpeed API Key pagespeed_api_key text (encrypted) Google PageSpeed Insights API key. Required for the Page Speed tab. Encrypted at rest via Secure_Store.
Enable URLs module urls_module_enabled checkbox Enables the URLs tab within the Performance page.
Enable URL data collection advana_urls_enable checkbox Enables active URL data collection. When disabled, existing data remains viewable but no new data is collected.

Reading Settings Programmatically

PHP
<?php
use ADVAN\Helpers\Settings;

// Check if the performance module is enabled
$enabled = Settings::get_option( 'performance_module_enabled' );

// Get the (decrypted) PageSpeed API key
$api_key = Settings::get_option( 'pagespeed_api_key' );

11. Caching Strategy

The Performance module uses two separate WordPress transients for caching:

Transient Key TTL Content Invalidation
aadvana_cached_pagespeed_api_data 1 hour (HOUR_IN_SECONDS) Normalized PageSpeed API response (mobile + desktop data + analysed URL) Auto-expires; overwritten on each fresh analysis
aadvana_site_checks_data 1 day (DAY_IN_SECONDS) Scanner results, score calculations, status percentages, cache timestamp Deleted and re-populated when user clicks “Re-run Site Health Checks” (nonce-protected)

Cache Priming Strategy

Site health checks are primed in the load-{page} hook (before admin_print_styles) to prevent session-token rotation issues. The scanner’s loopback HTTP requests can rotate auth cookies; running them after the REST nonce has been embedded in the page would cause 403 errors. By running the scanner early, the nonce generated later is always valid.

PageSpeed Auto-Load

On page load, pagespeed.js automatically requests cached data (?cached=1). If a cache hit occurs, results are rendered immediately without requiring a new API call.

12. Security Model

Capability Checks

  • manage_options enforced on: page rendering (analytics_performance_page()), all REST API endpoints (via check_permissions), and menu visibility (optionally via menu_admins_only)

Nonce Verification

Context Nonce Action Verification Method
REST API calls wp_rest WP REST nonce sent via X-WP-Nonce header
Site health refresh advan_refresh_checks wp_verify_nonce() on $_GET['_wpnonce']

Input Sanitization

  • URL input — sanitized via esc_url_raw(wp_unslash()) before passing to the Google API
  • Tab parameter — sanitized via sanitize_text_field(wp_unslash()) / sanitize_key()
  • API responses — HTML descriptions sanitized with regex-based markdown-to-HTML conversion; all output is escaped via esc_html() / esc_attr()

API Key Security

  • The pagespeed_api_key is encrypted at rest via the Secure_Store class
  • encrypt_sensitive_fields() encrypts the key on save
  • decrypt_sensitive_fields() decrypts on read, with transparent migration from plaintext to encrypted

External API Communication

  • All Google API requests use wp_remote_get() with a 300-second timeout
  • API categories requested: ACCESSIBILITY, BEST_PRACTICES, PERFORMANCE, PWA, SEO
  • Two requests per analysis: one for MOBILE strategy, one for DESKTOP
  • Response validation guards against empty, errored, or incomplete API responses

13. Diagnostics & Audit Mapping

The prepare_pagespeed_api_response() method maps Lighthouse audit IDs to Core Web Vital metric types. This mapping powers the audit filter system in the UI.

Audit ID Metrics Description
font-display FCP, LCP Font display strategy
critical-request-chains FCP, LCP Critical request chain length
largest-contentful-paint-element LCP LCP element identification
layout-shift-elements CLS Elements causing layout shifts
long-tasks TBT Long main-thread tasks
render-blocking-resources FCP, LCP Render-blocking CSS/JS
unused-css-rules FCP, LCP Unused CSS coverage
unminified-css FCP, LCP Unminified CSS files
unminified-javascript FCP, LCP Unminified JS files
unused-javascript LCP Unused JS coverage
uses-text-compression FCP, LCP Text compression (gzip/brotli)
uses-rel-preconnect FCP, LCP Preconnect to required origins
server-response-time FCP, LCP Server response time (TTFB)
redirects FCP, LCP HTTP redirects
uses-rel-preload FCP, LCP Preloading key requests
efficient-animated-content LCP Efficient animated content (video vs GIF)
duplicated-javascript TBT Duplicated JS modules
legacy-javascript TBT Legacy JS polyfills
total-byte-weight LCP Total page weight
dom-size TBT DOM element count
bootup-time TBT JS execution time
mainthread-work-breakdown TBT Main-thread work breakdown
third-party-summary TBT Third-party code impact
third-party-facades TBT Lazy-loadable third-party resources
non-composited-animations CLS Non-composited animations
unsized-images CLS Images without explicit dimensions
viewport TBT Viewport meta tag configuration

Audit Detail Rendering

The prepare_pagespeed_api_response() method filters audit details to only include renderable types:

  • Renderable detail types: table, opportunity, list, criticalrequestchain
  • Items: Limited to 20 per audit; only scalar-typed values are kept (url, source-location, bytes, ms, timespanMs, numeric, text, code, link)
  • Headings: Reduced to key, label, valueType triples

Screenshot Types

Key Data Source Description
final-screenshot details.data (base64) Final rendered page screenshot
full-page-screenshot details.screenshot.data (base64) Full-page screenshot
screenshot-thumbnails details.items[].data (base64) Filmstrip thumbnails with timestamp and timing data

14. Code Examples

Example 1: Check If PageSpeed API Key Is Configured

PHP
<?php
use ADVAN\Helpers\Settings;

$api_key = Settings::get_option( 'pagespeed_api_key' );

if ( empty( $api_key ) ) {
    echo 'PageSpeed API key is not configured.';
} else {
    echo 'PageSpeed API key is set and ready.';
}

Example 2: Fetch PageSpeed Data for a URL Programmatically

PHP
<?php
use ADVAN\Entities_Global\Common_Table;

$url  = 'https://example.com';
$data = Common_Table::fetch_pagespeed_for_url( $url );

if ( false === $data ) {
    echo 'Failed — no API key configured or API error.';
} else {
    // $data contains 'mobile_data' and 'desktop_data' arrays.
    $mobile_perf  = $data['mobile_data']['lighthouseResult']['categories']['performance']['score'] ?? null;
    $desktop_perf = $data['desktop_data']['lighthouseResult']['categories']['performance']['score'] ?? null;

    echo 'Mobile performance score: ' . ( $mobile_perf * 100 ) . '/100';
    echo 'Desktop performance score: ' . ( $desktop_perf * 100 ) . '/100';
}

Example 3: Read Cached PageSpeed Data

PHP
<?php
$cached = get_transient( 'aadvana_cached_pagespeed_api_data' );

if ( false !== $cached ) {
    $url = $cached['url'] ?? 'unknown';
    echo 'Cached PageSpeed data for: ' . $url;
} else {
    echo 'No cached PageSpeed data available.';
}

Example 4: Read Site Health Check Results

PHP
<?php
$cached = get_transient( 'aadvana_site_checks_data' );

if ( false !== $cached && is_array( $cached ) ) {
    $scores  = $cached['scores'];
    $results = $cached['results'];

    echo 'Overall score: ' . $scores['overall'] . '/100';
    echo 'Security: ' . $scores['security'] . '/100';
    echo 'Speed: ' . $scores['speed'] . '/100';
    echo 'Resources: ' . $scores['resources'] . '/100';

    echo 'Passed: ' . $scores['counts']['pass'];
    echo 'Warnings: ' . $scores['counts']['warning'];
    echo 'Failed: ' . $scores['counts']['fail'];

    // Iterate security checks
    foreach ( $results['security'] as $check ) {
        printf(
            "[%s] %s — %s\n",
            strtoupper( $check['status'] ),
            $check['title'],
            $check['message']
        );
    }
}

Example 5: Force-Refresh Site Health Checks Programmatically

PHP
<?php
use ADVAN\Checks\Scanner;
use ADVAN\Checks\Score_Calculator;

// Delete existing cache.
\delete_transient( 'aadvana_site_checks_data' );

// Run all 32 checks.
$results = Scanner::run_all();
$scores  = Score_Calculator::calculate( $results );

// Compute percentages.
$percentages = array( 'pass' => 0, 'warning' => 0, 'info' => 0, 'fail' => 0 );
if ( ! empty( $scores['counts']['total'] ) ) {
    $total = (int) $scores['counts']['total'];
    foreach ( array( 'pass', 'warning', 'info', 'fail' ) as $key ) {
        $percentages[ $key ] = (int) round( ( $scores['counts'][ $key ] / $total ) * 100 );
    }
}

// Re-cache.
\set_transient(
    'aadvana_site_checks_data',
    array(
        'results'     => $results,
        'scores'      => $scores,
        'percentages' => $percentages,
        'cached_at'   => time(),
    ),
    DAY_IN_SECONDS
);

echo 'Site health checks refreshed. Score: ' . $scores['overall'] . '/100';

Example 6: Use the REST API from JavaScript

JavaScript
// Fetch fresh PageSpeed data via the REST API.
makeRestRequest(
    'pagespeed_api_data/pagespeed_api_data?url=' + encodeURIComponent( 'https://example.com' ),
    {},
    'GET'
).then( function( response ) {
    if ( response.success && response.data ) {
        console.log( 'Mobile categories:', response.data.mobile_data.lighthouseResult.categories );
        console.log( 'Desktop categories:', response.data.desktop_data.lighthouseResult.categories );
    }
} );

Example 7: Collect PageSpeed for a Tracked URL

JavaScript
// Trigger per-URL PageSpeed collection from the URLs tab.
wp.apiFetch( {
    path: '/0-day/v1/collect_pagespeed/42',
    method: 'POST',
} ).then( function( response ) {
    if ( response.success ) {
        console.log( 'PageSpeed collected and persisted for URL #42' );
    }
    if ( response.errors && response.errors.length ) {
        console.warn( 'Errors:', response.errors );
    }
} );
Need User Guide documentation?
See Performance Module User Guide for more details about configuration, practical usage and information.
← Performance Module — User Guide 10 Lesser-Known WordPress Security Practices →
Share this page
Back to top