Skip to main content

WPW Mermaid JS

Overview

Version 0.1.0 by OpenCode. Adds Mermaid diagram support to WordPress posts and pages with:

  • Gutenberg block (wpstrategist/mermaid) with live preview
  • Raw content rendering (HTML code blocks and fenced code blocks)
  • Server-side SVG generation with caching
  • WP-CLI commands for batch rendering

Rendering Pipeline

Post content
→ Block: render_block('wpstrategist/mermaid') → SSR SVG or client JS
→ Raw HTML: <code class="language-mermaid"> → SSR SVG or client JS
→ Fenced: ```mermaid ``` → SSR SVG or client JS
→ SVG available? Serve cached SVG <img>
→ No SVG? Fall back to client-side rendering via Mermaid JS

Gutenberg Block

Registered as wpstrategist/mermaid with:

  • Editor script: assets/js/editor.js (live Mermaid preview in block editor)
  • Frontend script: assets/js/frontend.js
  • Styles: editor.css and frontend.css

Block attribute:

AttributeTypeDefaultDescription
codestring""Mermaid diagram source code

SVG SSR Caching

On post save (save_post hook), Mermaid codes are extracted and SVGs are generated via mmdc (Mermaid CLI):

$hash = md5($code);
$file = wp_upload_dir() . '/wpstrategist-mermaid/' . $hash . '.svg';

If the SVG file exists, it's served as an <img> with a ?v=filemtime cache buster. If generation fails, the diagram falls back to client-side rendering using the Mermaid JS runtime library.

CLI Binary Resolution

The mmdc command is resolved in order:

  1. Local node_modules/.bin/mmdc
  2. Global mmdc binary
  3. npx -y @mermaid-js/mermaid-cli

Browser path resolved from: chromiumgoogle-chromegoogle-chrome-stable

Frontend Detection

Assets are only enqueued when content actually contains Mermaid:

  • Block: wpstrategist/mermaid in block markup
  • HTML: language-mermaid class in code blocks
  • Fenced: ```mermaid in raw content

WP-CLI Commands

CommandDescription
wp mermaid render <post-id>Generate SVG assets for all Mermaid diagrams in a post
wp mermaid testTest SVG generation with a sample diagram (default: graph TD)

Content Extraction

wpstrategist_mermaid_get_mermaid_codes_from_content() extracts diagrams from all three formats:

  • Block attributes
  • HTML code blocks with language-mermaid
  • Fenced code blocks with ```mermaid

CDN Configuration

Default Mermaid JS CDN: https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js

Filterable via wpstrategist_mermaid_cdn_url filter.