Caching & Transients

cwpCacheData($key, $data = null, $expire = 3600)

Set or get cached data using WordPress transients.

  • Set cache:
    cwpCacheData('my_key', $data, 3600); // Cache for 1 hour
  • Get cache:
    $data = cwpCacheData('my_key');
  • Parameters:
    • $key (string): Unique cache key
    • $data (mixed): Data to cache (if null, function returns cached value)
    • $expire (int): Expiry in seconds (default: 1 hour)

cwpClearCache($key)

Clear cached data by key.

  • Usage:
    cwpClearCache('my_key');
  • Parameters:
    • $key (string): Cache key to clear

cwp_cache_bust($url, $version = null)

Append a cache-busting query string to asset URLs to force browsers to reload updated files.

  • Usage:

    // Using file modification time (recommended)
    $url = cwp_cache_bust(get_stylesheet_directory_uri() . '/style.css');
    
    // Using custom version
    $url = cwp_cache_bust(get_stylesheet_directory_uri() . '/script.js', '1.2.3');
  • Parameters:

    • $url (string): The asset URL to modify
    • $version (string|int, optional): Version or timestamp. If null, uses file modification time or current timestamp
  • Returns: Cache-busted URL string, or false if URL is invalid


cwpIsURLValid($data, $logging = false, $checkCount = 1, $random = false)

Purpose: Quickly check whether cached FileMaker responses contain expired Streaming_SSL image URLs so you can decide whether to repopulate the cache before a page renders. This function performs a small, fast set of HTTP checks and returns a boolean.

Signature and parameters (each parameter listed):

  • $data (string|array) — REQUIRED: A URL string or a FileMaker response array. The function will recursively scan arrays for values containing the substring Streaming_SSL (case-insensitive).
  • $logging (bool) — OPTIONAL: true/false. If true, failures are recorded to the CWP Pro custom log via cwpLog() (category cwp_image_invalid). Default: false.
  • $checkCount (int) — OPTIONAL: number of Streaming_SSL image URLs to validate. Default: 1.
  • $random (bool) — OPTIONAL: true/false. When true, the function samples $checkCount URLs at random from the found candidates; when false it uses the first $checkCount URLs found. Default: false.

Behavior:

  • The function scans $data for values containing Streaming_SSL and collects candidate URLs.
  • If no candidates are found the function returns true immediately (nothing to validate).
  • Otherwise it selects up to $checkCount URLs (randomly if $random is true) and performs an HTTP HEAD request for each; if HEAD fails it retries once with GET.
  • The function returns true only if all sampled URLs return a 2xx response; it returns false on the first failing sampled URL.

Examples:

  • Check a single cached response with logging enabled (default behavior):

    $cached = cwpCacheData('fm_records');
    if ($cached && cwpIsURLValid($cached, true)) {
    // cached response OK
    } else {
    // refresh cache
    }
  • Check 3 random Streaming_SSL images from a cached response:

    if (!cwpIsURLValid($cachedResponse, true, 3, true)) {
    // one or more sampled URLs failed — refresh cache
    }

Notes:

  • Uses short timeouts and sslverify => false for resiliency in some environments.
  • Designed as a lightweight boolean pre-flight check; increase $checkCount only when necessary as it adds network overhead.

REST API Endpoint: Clear Cache

POST /wp-json/cwp/v1/clear-cache

Allows external apps (e.g., FileMaker) to clear a cache key via REST API.

  • Usage: POST to /wp-json/cwp/v1/clear-cache with JSON body:
    {
      "cache_key": "your_key",
      "token": "your_token" // optional, add your own auth logic
    }
  • Security: Add your own token/auth logic in the permission_callback
  • Response:
    • Success: { success: true, message: "Cache 'your_key' cleared." }
    • Error: { success: false, message: "..." }

Wildcard prefix & multiple-key behavior

The REST clear-cache endpoint now supports the following additional input shapes:

  • Single key (string): {"cache_key":"my_key"} — clears the exact key.
  • Multiple keys (array): {"cache_key":["key1","key2"]} — clears each entry; wildcard entries are supported inside the array.
  • Delimiter-separated string: {"cache_key":"key1, key2, prefix_*"} — accepts comma, semicolon or CR/LF separated values and will split them into multiple keys.

Wildcard prefixes: any key ending with * is treated as a prefix wildcard. For example, alex_* will delete all transients whose logical key begins with alex_ under the CWP_TRANSIENT_PREFIX namespace.

Important behavior changes:

  • Wildcard deletions execute immediately (there is no dry_run option). Use caution — these operations are destructive.
  • For safety, wildcard deletions are limited to a default maximum number of matches (default: 25). If more keys match, only the first N (alphabetically) are processed and a warning is returned in the helper response.

Example — wildcard prefix delete:

curl -X POST https://example.com/wp-json/cwp/v1/clear-cache \
  -H "Content-Type: application/json" \
  -d '{"cache_key":"alex_*","token":"<your_token>"}'

Example — multiple keys including a wildcard:

curl -X POST https://example.com/wp-json/cwp/v1/clear-cache \
  -H "Content-Type: application/json" \
  -d '{"cache_key":["alex_*","other_key"],"token":"<your_token>"}'

Response for a wildcard request (example):

{
  "success": true,
  "result": {
    "matched": 3,
    "deleted": 3,
    "matched_keys": ["alex_1","alex_2","alex_meta"],
    "warning": null
  },
  "message": "Processed wildcard prefix."
}

Security note: because wildcard deletes now act immediately, protect the endpoint with a permission_callback or other authentication (Bearer token, capability checks, IP allowlist, etc.).


Clear All: REST flag & Admin AJAX

You can clear all CWP-prefixed transients either via the REST endpoint or via an admin AJAX action. Both call cwpClearAllTransients() and return the number of transients deleted.

  • REST (external/automation):

    • Use the existing endpoint POST /wp-json/cwp/v1/clear-cache with either:
      • { "clear_all": true } or
      • { "cache_key": "__all__" }
    • The clear-all action is intentionally permissive by default; implementers can add their own permission or token checks in the REST permission_callback if desired. The endpoint will return:
      { "success": true, "deleted": 12, "message": "Deleted 12 transients." }
  • Admin AJAX (admin UI):

    • Endpoint: admin-ajax.php with action=cwp_clear_all_transients
    • Required POST fields: nonce (your cwp_universal_nonce) and confirm=1 to avoid accidental clears.
    • Example JS (admin page):
      jQuery.post(ajaxurl, {
        action: 'cwp_clear_all_transients',
        nonce: CWP.universalNonce,
        confirm: '1'
      }, function(resp){
        console.log(resp);
      });

Security notes:

  • Both methods enforce admin capability for destructive clear_all actions. The REST route currently returns true for permission_callback (no token) but the clear-all path explicitly checks current_user_can('manage_options') before proceeding. Consider adding token/auth later for external automation.

FileMaker integration & quick examples

If you're triggering cache clears from FileMaker (Insert from URL), here are a few practical options.

  • REST JSON POST (recommended):
    • URL: https://your-site/wp-json/cwp/v1/clear-cache
    • Example cURL options (paste in the Insert from URL cURL box):
--request POST --header "Content-Type: application/json" --data "{\"clear_all\":true}" --max-time 30
  • If you prefer to build the cURL options with a FileMaker calculation (no manual escaping), use a Let calculation and Quote() / JSONSetElement():
Let(
  [
    json = JSONSetElement("{}"; "clear_all"; True; JSONBoolean);
    curl = "--request POST " &
           "--header " & Quote("Content-Type: application/json") & " " &
           "--data " & Quote(json) & " " &
           "--max-time 30"
  ];
  curl
)
  • To include a token in the JSON body: add JSONSetElement() entries for token or append --header "Authorization: Bearer <token>" using Quote().

  • Admin-AJAX (simple backdoor / quick test):

    • URL (GET): https://your-site/wp-admin/admin-ajax.php?action=cwp_clear_cache&clear_all=1
    • Or POST (form-encoded):
--request POST --header "Content-Type: application/x-www-form-urlencoded" --data "clear_all=1" --max-time 30
  • From FileMaker you can either place the query string in the URL field (no cURL options needed) or send the POST body via the cURL options box.

Notes about escaping in FileMaker

  • If you paste raw cURL options into the cURL box, JSON double-quotes must be escaped (e.g., \"clear_all\":true).
  • Use Quote() and JSONSetElement() in a calculation to avoid manual escaping and to produce valid JSON automatically.

Why JSON vs form-encoded

  • The REST endpoint expects JSON and will parse the body automatically when Content-Type is application/json. Admin-AJAX can accept form-encoded parameters and is convenient for quick tests.

Safety & recommendations

  • The REST route and the simple AJAX handler are intentionally permissive in this codebase for convenience and testing. In production, prefer:
    • A long unguessable token validated in permission_callback or inside the handler; or
    • Restrict access by IP/network; or
    • Require an authenticated admin request (remove nopriv registration).
  • Add logging (cwpLog) for any external clears so you can audit who/when cleared caches.

Transient Expiry Viewer

cwpShowTransients()

Purpose:

  • Displays all current CWP transients (cache items) and their expiry times.
  • Only visible to users with manage_options capability (admins/webmasters).

Usage:

cwpShowTransients();

Security Note:

  • This function is for debugging and admin use only. It is not visible to regular users.
  • The code does not reveal or hint at any sensitive or private transients.