Home / Widgets / AI Buzz — Auto Article Count
Duplicate Snippet

Embed Snippet on Your Site

AI Buzz — Auto Article Count

Code Preview
js
/**
 * AI BUZZ — AUTO ARTICLE COUNT UPDATER
 *
 * Automatically updates any element with id="aibuzz-article-count"
 * on the page with the current total number of published articles.
 *
 * Uses localStorage to cache the count for 24 hours.
 * Only calls the WordPress REST API when the cache is stale.
 * Falls back gracefully if the API is unavailable.
 */
(function () {
  'use strict';
  // ── CONFIGURATION ────────────────────────────────────────
  var CACHE_KEY      = 'aibuzz_post_count';
  var CACHE_EXPIRY   = 'aibuzz_post_count_expiry';
  var CACHE_HOURS    = 24;
  var CACHE_DURATION = CACHE_HOURS * 60 * 60 * 1000; // 24 hours in ms
  var API_URL        = 'https://aibuzz.blog/wp-json/wp/v2/posts'
                     + '?status=publish&per_page=1&_fields=id';
  var TARGET_ID      = 'aibuzz-article-count';
  // ── FIND THE TARGET ELEMENT ───────────────────────────────
  var targetElement = document.getElementById(TARGET_ID);
  // If no element with this ID exists on the page, do nothing.
  // This prevents unnecessary API calls on non-homepage pages.
  if (!targetElement) {
    return;
  }
  // ── UPDATE DISPLAY ────────────────────────────────────────
  function updateDisplay(count) {
    if (targetElement && count > 0) {
      targetElement.textContent = count;
    }
  }
  // ── FETCH FROM WORDPRESS REST API ────────────────────────
  // Uses the X-WP-Total response header which returns the
  // total post count without fetching any post content.
  // This is the lightest possible API call.
  function fetchCountFromAPI() {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', API_URL, true);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          var total = xhr.getResponseHeader('X-WP-Total');
          if (total) {
            var count = parseInt(total, 10);
            if (!isNaN(count) && count > 0) {
              // Save to localStorage cache
              try {
                localStorage.setItem(CACHE_KEY, count.toString());
                localStorage.setItem(
                  CACHE_EXPIRY,
                  (Date.now() + CACHE_DURATION).toString()
                );
              } catch (storageError) {
                // localStorage unavailable — proceed without caching
              }
              updateDisplay(count);
            }
          }
        }
        // If API fails silently, the fallback number in HTML remains
      }
    };
    xhr.onerror = function () {
      // Network error — fallback number in HTML remains visible
    };
    xhr.send();
  }
  // ── CHECK CACHE FIRST ─────────────────────────────────────
  // If a fresh cached count exists, use it immediately.
  // No API call needed for the next 24 hours.
  try {
    var cachedCount  = localStorage.getItem(CACHE_KEY);
    var cacheExpiry  = localStorage.getItem(CACHE_EXPIRY);
    var cacheIsValid = cachedCount
                    && cacheExpiry
                    && Date.now() < parseInt(cacheExpiry, 10);
    if (cacheIsValid) {
      var count = parseInt(cachedCount, 10);
      if (!isNaN(count) && count > 0) {
        updateDisplay(count);
        return; // Cache is fresh — no API call needed
      }
    }
  } catch (storageError) {
    // localStorage unavailable — fall through to API call
  }
  // ── CACHE STALE OR EMPTY — FETCH FROM API ─────────────────
  fetchCountFromAPI();
})();

Comments

Add a Comment