Search by

giantpeach / wp-modern-images

Giant Peach

Improved developer experience for working with WordPress media library images

Package info

github.com/Giant-Peach-Design/wp-modern-images

Type:wordpress-plugin

pkg:composer/giantpeach/wp-modern-images

Statistics

Installs: 361

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

v1.2.1 2026-12-02 14:49 UTC

This package is auto-updated.

Last update: 2026-12-03 09:22:19 UTC


README

A WordPress plugin for generating responsive <picture> elements with WebP support, retina handling, and art direction capabilities.

Installation

composer require giantpeach/wp-modern-images

After installation, activate the plugin and flush permalinks (Settings → Permalinks → Save).

Usage

echo gp_image(123, [
    0 => [
        'w' => 400,
        'h' => 300,
    ],
    768 => [
        'w' => 800,
        'h' => 600,
    ],
    1024 => [
        'w' => 1200,
        'h' => 800,
    ],
]);

Parameters

gp_image(int $image_id, array $sizes, array $options = []): string

Parameter Type Description
$image_id int WordPress attachment ID
$sizes array Breakpoint-keyed array of size configurations
$options array Optional rendering options

Size Configuration

Array keys define the min-width breakpoint in pixels (0 = default/mobile):

$sizes = [
    0 => [                    // Default (mobile)
        'w' => 400,           // Width (required)
        'h' => 300,           // Height (required)
        'fit' => 'cover',     // Fit mode (default: 'cover')
        'q' => 80,            // Quality 1-100 (default: 80)
    ],
    768 => [                  // min-width: 768px
        'w' => 800,
        'h' => 600,
    ],
    1024 => [                 // min-width: 1024px
        'w' => 1200,
        'h' => 800,
        'image_id' => 456,    // Art direction: use different image
    ],
];

Fit Modes

Value Description
cover Fill dimensions, crop excess (like CSS object-fit: cover)
contain Fit within dimensions, maintain aspect ratio
fill Stretch to exact dimensions

Options

$options = [
    'retina' => true,           // Generate 2x versions (default: true)
    'picture_class' => '',      // Class for <picture> element
    'img_class' => '',          // Class for <img> element
    'alt' => '',                // Alt text (defaults to WP attachment alt)
    'loading' => 'lazy',        // 'lazy' or 'eager'
];

Full Example

echo gp_image(123, [
    0 => [
        'w' => 400,
        'h' => 300,
        'fit' => 'cover',
        'q' => 85,
    ],
    768 => [
        'w' => 800,
        'h' => 600,
        'fit' => 'cover',
    ],
    1024 => [
        'w' => 1200,
        'h' => 800,
        'fit' => 'contain',
        'q' => 90,
        'image_id' => 456,
    ],
], [
    'picture_class' => 'hero',
    'img_class' => 'hero__img',
    'loading' => 'eager',
]);

Output

<picture class="hero">
    <source media="(min-width: 1024px)" srcset="...-1200x800.webp 1x, ...-2400x1600.webp 2x" type="image/webp">
    <source media="(min-width: 1024px)" srcset="...-1200x800.jpg 1x, ...-2400x1600.jpg 2x" type="image/jpeg">
    <source media="(min-width: 768px)" srcset="...-800x600.webp 1x, ...-1600x1200.webp 2x" type="image/webp">
    <source media="(min-width: 768px)" srcset="...-800x600.jpg 1x, ...-1600x1200.jpg 2x" type="image/jpeg">
    <source srcset="...-400x300.webp 1x, ...-800x600.webp 2x" type="image/webp">
    <img src="...-400x300.jpg" srcset="...-400x300.jpg 1x, ...-800x600.jpg 2x" alt="..." class="hero__img" loading="eager">
</picture>

Blade Directive (Sage/Acorn)

If you're using Sage with Acorn, add this to your app/Providers/ThemeServiceProvider.php in the boot() method:

\Illuminate\Support\Facades\Blade::directive('gpImage', function ($expression) {
    return "<?php echo gp_image({$expression}); ?>";
});

Then use in your Blade templates:

@gpImage(123, [
    0 => ['w' => 400, 'h' => 300],
    768 => ['w' => 800, 'h' => 600],
    1024 => ['w' => 1200, 'h' => 800],
])

{{-- With options --}}
@gpImage($image_id, $sizes, ['picture_class' => 'hero', 'img_class' => 'hero__img'])

How images are built

Rendering gp_image() never processes an image. Each variant gets a URL under /img/; if the variant is already cached that URL is served straight from the cache, and if not, the URL carries signed build parameters (?iw=…&ih=…&fit=…&fm=…&q=…&sig=…) and the variant is built on its first request. The URL is the same either way, so page caches stay valid.

Builds are kept cheap and bounded:

  • Only one request builds a given variant; others wait a few seconds for it.
  • At most 2 variants build at once per site (gp_modern_images_max_concurrent).
  • When busy, or if a build fails, the request is redirected (302, uncached) to the original upload so the visitor still sees the image. Failed variants are not retried for 10 minutes.
  • Sizes are never upscaled past the source image (retina 2x included).
  • GIFs are output as a plain <img> of the original upload and never processed: resizing an animated GIF resizes every frame (minutes and gigabytes for a 750px banner) and would lose the animation anyway.
  • ImageMagick runs single-threaded and keeps its temp files in the work directory, which an hourly cron job cleans.

Unsigned or tampered build URLs return 404, so nobody can ask the server to render arbitrary sizes.

WP-CLI

wp modern-images warm                     # build every variant pages have asked for but that isn't built yet
wp modern-images warm --attachment=123    # just one attachment's variants
wp modern-images status                   # cache size, pending queue, temp files
wp modern-images clean                    # remove temp files, stale locks, failure markers
wp modern-images clean --cache --yes      # also delete every built variant

Variants join the pending queue the first time a page renders them, so visit the page (or let traffic do it) and then run warm to build them from the CLI instead of in visitors' requests.

Serving cached images from nginx (recommended)

The /img/ route works without any server config, but every image request then boots WordPress (~0.25s each). Cached variants are plain files with the right extension, so let nginx serve them directly and only send misses to PHP. Add this inside the site's server {} block, before the location ~ \.php$ block. Adjust the path if the cache isn't in <web root>/app/wp-modern-images-cache (Bedrock); for standard WordPress it's /wp-content/wp-modern-images-cache/:

# WP Modern Images: serve built variants from disk; misses go to WordPress.
location ~ ^/img/(.+)$ {
    access_log off;
    add_header Cache-Control "public, max-age=31536000, immutable";
    add_header X-Content-Type-Options "nosniff";
    try_files /app/wp-modern-images-cache/$1 /index.php?$query_string;
}

Cache Directory

By default, processed images are cached in wp-content/wp-modern-images-cache/.

Don't put the cache inside wp-content/cache/. Page-cache plugins treat that directory as their own: WP Super Cache's garbage collector deletes anything in it older than its cache lifetime, which throws away every built variant. (1.1.0 and earlier used wp-content/cache/wp-modern-images/; that directory can be deleted after upgrading.)

Via constant:

define('WP_MODERN_IMAGES_CACHE_DIR', '/path/to/cache');
define('WP_MODERN_IMAGES_CACHE_URL', 'https://example.com/cache');

Via filter:

add_filter('gp_modern_images_cache_path', function($path) {
    return '/custom/cache/path';
});

Work Directory

Locks, temp files, failure markers and the pending queue live beside the cache in wp-content/wp-modern-images-cache-work/. Nothing links to it, but it is inside wp-content, so point it outside the web root if that matters to you. Override with WP_MODERN_IMAGES_WORK_DIR or the gp_modern_images_work_path filter.

Signing Key

Build URLs are signed with a key derived from wp_salt('auth'). Set WP_MODERN_IMAGES_SIGN_KEY to use your own; changing either invalidates signed URLs in cached pages (they will 404 until the pages are regenerated).

Filters

Filter Description
gp_modern_images_cache_path Modify cache directory path
gp_modern_images_cache_url Modify cache directory URL
gp_modern_images_default_options Modify default options
gp_modern_images_picture_html Modify final HTML output
gp_modern_images_work_path Modify the work directory path
gp_modern_images_max_concurrent Max variants built at once per site (default 2)
gp_modern_images_lock_wait Seconds to wait for another request building the same variant (default 5)
gp_modern_images_max_image_size Max output size in pixels, w×h (default 4096×4096)

Requirements

  • PHP 7.4+
  • WordPress 5.0+
  • GD or Imagick extension

License

MIT