Contents
Introduction
This tutorial explains how to generate images on-the-fly in WordPress using PHP, and how to cache them efficiently and safely so repeated requests are fast and cheap. It covers two common approaches (pretty URL rewrite generator, and REST API endpoint), demonstrates real, copy-paste-ready code examples, and walks through security, performance, caching headers (ETag / If-Modified-Since), file storage, and troubleshooting tips.
What youll learn
- How to create a dynamic image generator using GD (and an alternative using Imagick)
- How to integrate generation into WordPress (rewrite rule template_redirect, and a REST API route)
- How to cache generated images on disk, validate and serve them with proper HTTP cache headers and conditional GET
- Security and performance best practices and common pitfalls
Prerequisites
- WordPress (any recent version)
- PHP 7.0 recommended (GD extension or Imagick extension installed)
- Filesystem write access for WordPress uploads directory (or plugin-specific cache dir)
- Font file (for TTF text rendering) if using imagettftext
Design and approach overview
We want a flow that:
- Parses request parameters (width, height, text, colors, source image, etc.) in a controlled way
- Computes a deterministic cache key for those parameters
- If a cached file exists, serve it with HTTP caching headers and conditional GET support (304 when possible)
- If no cached file exists, generate the image (GD or Imagick), save it to cache, then serve it
- Protect against injection, path traversal, oversized images, and excessive server resources
Where to cache images
Use WordPresss uploads directory for cache storage so the web server can serve cached files if desired and so files survive plugin/theme updates. You can create a subfolder such as wp-content/uploads/dynamic-images. Use wp_upload_dir() and wp_mkdir_p() to create and manage the folder.
Core concepts to implement
- Deterministic filename generation: hash relevant parameters such as width, height, text, color, source image path, retina flag, and quality
- Atomic file writes: write to a temp file then rename to avoid partially-written files
- Conditional GET: ETag and Last-Modified checks to return 304 when unchanged
- Cache TTL: set long max-age for generated static outputs and optionally purge older files on schedule
- Input validation: strictly validate numeric sizes, color hex codes, font names, and allowed actions
- Resource limits: cap width and height, prevent huge memory allocation, use set_time_limit or handle errors gracefully
Example 1 — A complete plugin: pretty URL generator using GD
This plugin registers a pretty rewrite rule like /image-gen/200×100/Hello-world.png. It parses width, height and text from the URL, generates (or caches) a PNG, and serves it with correct headers and conditional GET support.
Save this file as a small plugin (e.g., dynamic-image-gen.php) in wp-content/plugins/dynamic-image-gen/. Activate the plugin, then visit a generated URL to test.
lt?php
/
Plugin Name: Dynamic Image Generator (example)
Description: Generate images on-the-fly and cache them. Example implementation using GD.
Version: 1.0
Author: Example
/if ( ! defined( ABSPATH ) ) {
exit
}/
Register rewrite rule on init.
Pattern: /image-gen/{WIDTH}x{HEIGHT}/{TEXT}.png
/
add_action( init, function() {
add_rewrite_rule(
^image-gen/([0-9]{1,4})x([0-9]{1,4})/([^/] ).(pngjpgjpeg)
|
Acepto donaciones de BAT's mediante el navegador Brave :) |