Tutorial

Screenshot API for WordPress: Capture & Embed

Capture website screenshots from WordPress on the server, store them in the Media Library, and embed them with a cached shortcode.

Asad AliOctober 12, 20259 min read

WordPress sites use website screenshots for resource directories, portfolio pages, "sites we built" galleries and link roundups. This tutorial builds a small must-use plugin that does three things:

  1. Calls the Screenshotly API from PHP on your server, so the API key never reaches a browser.
  2. Saves each capture to the Media Library, so visitors load an ordinary image from your own site.
  3. Adds a [screenshot] shortcode that never waits on the API during a page view. A missing or stale capture is queued in the background.

Everything here uses core WordPress functions (wp_remote_post, wp_upload_bits, wp_insert_attachment, wp_schedule_single_event). No third-party plugin is needed, and Screenshotly does not ship an official WordPress plugin.

What you need

  • A Screenshotly API key. The free plan includes 100 captures in total, at up to 5 requests per minute, with PNG, JPEG and WebP output. Every capture and every refresh counts as one capture, so plan your refresh interval with that in mind (pricing).
  • WordPress with WP-Cron working, or a real system cron calling wp-cron.php.
  • Pages you want to capture must be publicly reachable. The API rejects private and internal addresses.

Step 1: Store the API key in wp-config.php

// wp-config.php, above "That's all, stop editing!"
define( 'SCREENSHOTLY_API_KEY', 'your-api-key' );

A constant keeps the key out of the wp_options table, so it does not end up in database dumps, staging copies or export files.

Step 2: Call the API from PHP

The endpoint is POST https://screenshotly.app/api/screenshot. Send a JSON body and the key in an x-api-key header (Authorization: Bearer <key> also works). A successful response is the image itself, with Content-Type: image/png (or image/jpeg, image/webp). Errors come back as JSON with an error and usually a message field.

Create wp-content/mu-plugins/screenshotly.php:

<?php
/**
 * Plugin Name: Screenshotly captures
 * Description: Server-side website screenshots stored in the Media Library.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

const SCREENSHOTLY_ENDPOINT = 'https://screenshotly.app/api/screenshot';

/**
 * Capture a URL and return the image bytes, or a WP_Error.
 */
function screenshotly_capture( string $url, array $options = [] ) {
    if ( ! defined( 'SCREENSHOTLY_API_KEY' ) ) {
        return new WP_Error( 'screenshotly_no_key', 'SCREENSHOTLY_API_KEY is not defined.' );
    }

    $body = array_merge(
        [
            'url'    => $url,
            'width'  => 1280,
            'height' => 800,
            'format' => 'png',
        ],
        $options
    );

    $response = wp_remote_post(
        SCREENSHOTLY_ENDPOINT,
        [
            'headers' => [
                'x-api-key'    => SCREENSHOTLY_API_KEY,
                'Content-Type' => 'application/json',
            ],
            'body'    => wp_json_encode( $body ),
            // The WordPress default is 5 seconds. A capture can take up to ~30.
            'timeout' => 45,
        ]
    );

    if ( is_wp_error( $response ) ) {
        return $response;
    }

    $status = (int) wp_remote_retrieve_response_code( $response );
    $type   = (string) wp_remote_retrieve_header( $response, 'content-type' );
    $bytes  = wp_remote_retrieve_body( $response );

    if ( 200 !== $status || 0 !== strpos( $type, 'image/' ) ) {
        $error = json_decode( $bytes, true );
        $text  = is_array( $error )
            ? trim( ( $error['error'] ?? '' ) . ': ' . ( $error['message'] ?? '' ), ': ' )
            : 'Unexpected response';
        return new WP_Error( 'screenshotly_http_' . $status, $text, [ 'status' => $status ] );
    }

    return [ 'bytes' => $bytes, 'type' => $type ];
}

Notes on the request body:

  • width (320–3840) and height (240–3840) are top-level fields. There is no nested viewport object, and the API rejects unknown fields with a 400.
  • You can use device (desktop, laptop, tablet, mobile) instead of width/height.
  • format can be png, jpeg or webp on every plan. jpeg and webp also accept quality (0–100).
  • Viewport captures skip web-font downloads to save time, so headings can render in a fallback system font. If typography matters more than framing, send fullPage: true, which loads web fonts, and crop the result in WordPress.

Step 3: Save the image to the Media Library

Add these functions to the same file. Each capture is stored as an attachment, tagged with a hash of the URL and options so the plugin can find it again:

function screenshotly_key( string $url, array $options ): string {
    return md5( $url . '|' . wp_json_encode( $options ) );
}

function screenshotly_find_attachment( string $key ): int {
    $ids = get_posts(
        [
            'post_type'      => 'attachment',
            'post_status'    => 'inherit',
            'meta_key'       => '_screenshotly_key',
            'meta_value'     => $key,
            'fields'         => 'ids',
            'posts_per_page' => 1,
            'no_found_rows'  => true,
        ]
    );
    return $ids ? (int) $ids[0] : 0;
}

function screenshotly_store( string $url, array $options, array $capture ) {
    $extensions = [ 'image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp' ];
    $mime       = strtok( $capture['type'], ';' );
    $ext        = $extensions[ $mime ] ?? 'png';
    $key        = screenshotly_key( $url, $options );

    $upload = wp_upload_bits( "screenshot-{$key}.{$ext}", null, $capture['bytes'] );
    if ( ! empty( $upload['error'] ) ) {
        return new WP_Error( 'screenshotly_upload', $upload['error'] );
    }

    $attachment_id = wp_insert_attachment(
        [
            'post_mime_type' => $mime,
            'post_title'     => 'Screenshot of ' . $url,
            'post_status'    => 'inherit',
        ],
        $upload['file']
    );
    if ( is_wp_error( $attachment_id ) ) {
        return $attachment_id;
    }

    require_once ABSPATH . 'wp-admin/includes/image.php';
    wp_update_attachment_metadata(
        $attachment_id,
        wp_generate_attachment_metadata( $attachment_id, $upload['file'] )
    );
    update_post_meta( $attachment_id, '_screenshotly_key', $key );
    update_post_meta( $attachment_id, '_screenshotly_source', esc_url_raw( $url ) );
    update_post_meta( $attachment_id, '_screenshotly_captured', time() );

    return (int) $attachment_id;
}

wp_generate_attachment_metadata() creates the usual intermediate sizes, so wp_get_attachment_image() can output a responsive srcset later without any extra API calls.

Step 4: Capture in the background

Page views should never wait for a capture, which can take up to about 30 seconds. The shortcode queues a WP-Cron event instead, and the event does the work. Add this to the same file:

const SCREENSHOTLY_MAX_AGE = 30 * DAY_IN_SECONDS;

function screenshotly_queue_capture( string $url, array $options = [] ): void {
    $args = [ $url, $options ];
    if ( ! wp_next_scheduled( 'screenshotly_capture_event', $args ) ) {
        wp_schedule_single_event( time() + 10, 'screenshotly_capture_event', $args );
    }
}

add_action( 'screenshotly_capture_event', 'screenshotly_run_capture', 10, 2 );

function screenshotly_run_capture( string $url, array $options = [] ): void {
    $capture = screenshotly_capture( $url, $options );
    if ( is_wp_error( $capture ) ) {
        error_log( 'Screenshotly capture failed for ' . $url . ': ' . $capture->get_error_message() );
        return;
    }

    $previous = screenshotly_find_attachment( screenshotly_key( $url, $options ) );
    $stored   = screenshotly_store( $url, $options, $capture );

    // Replace the old copy only after the new one is saved.
    if ( ! is_wp_error( $stored ) && $previous ) {
        wp_delete_attachment( $previous, true );
    }
}

WP-Cron only runs when someone visits the site. On low-traffic sites, set define( 'DISABLE_WP_CRON', true ); and call wp-cron.php from a system cron every few minutes, so queued captures do not wait for a visitor.

Failed captures are logged and not retried automatically. The next page view that needs the image queues it again. A 429 means you hit the per-minute request rate or ran out of monthly (or, on the free plan, total) captures. The JSON message says which.

Step 5: The shortcode

The last part of the file:

// [screenshot url="https://example.com" width="1280" height="800" alt="Example homepage"]
add_shortcode( 'screenshot', 'screenshotly_shortcode' );

function screenshotly_shortcode( $atts ): string {
    $atts = shortcode_atts(
        [
            'url'    => '',
            'width'  => 1280,
            'height' => 800,
            'alt'    => '',
        ],
        $atts,
        'screenshot'
    );

    $url = esc_url_raw( $atts['url'], [ 'http', 'https' ] );
    if ( ! $url || ! wp_http_validate_url( $url ) ) {
        return '';
    }

    $options = [
        'width'  => min( 3840, max( 320, (int) $atts['width'] ) ),
        'height' => min( 3840, max( 240, (int) $atts['height'] ) ),
    ];

    $attachment_id = screenshotly_find_attachment( screenshotly_key( $url, $options ) );
    $captured      = $attachment_id ? (int) get_post_meta( $attachment_id, '_screenshotly_captured', true ) : 0;

    if ( ! $attachment_id || ( time() - $captured ) > SCREENSHOTLY_MAX_AGE ) {
        screenshotly_queue_capture( $url, $options );
    }

    if ( ! $attachment_id ) {
        // Nothing captured yet: show a plain link until the background job finishes.
        return sprintf( '<a href="%s" rel="noopener">%s</a>', esc_url( $url ), esc_html( $url ) );
    }

    $image = wp_get_attachment_image(
        $attachment_id,
        'large',
        false,
        [ 'alt' => $atts['alt'] ?: 'Screenshot of ' . $url, 'loading' => 'lazy' ]
    );

    return sprintf( '<a href="%s" rel="noopener">%s</a>', esc_url( $url ), $image );
}

How it behaves:

  • First view: the visitor sees a link, and a capture is queued.
  • Later views: the visitor gets a normal Media Library image with srcset and loading="lazy". No API call is made.
  • After 30 days: the old image is still shown while a refresh runs in the background. Change SCREENSHOTLY_MAX_AGE to suit how often the pages change. Each refresh uses one capture.

Anyone who can add a shortcode, including Contributors, can make your site capture any public URL, and each capture uses your quota. On multi-author sites, check the host against an allowlist before calling screenshotly_queue_capture().

Optional: refresh from WP-CLI

if ( defined( 'WP_CLI' ) && WP_CLI ) {
    WP_CLI::add_command(
        'screenshotly capture',
        function ( $args, $assoc_args ) {
            $options = [
                'width'  => (int) ( $assoc_args['width'] ?? 1280 ),
                'height' => (int) ( $assoc_args['height'] ?? 800 ),
            ];
            screenshotly_run_capture( $args[0], $options );
            WP_CLI::success( 'Capture attempted for ' . $args[0] . '. Check the PHP error log for failures.' );
        }
    );
}

wp screenshotly capture https://example.com --width=1280 --height=800 captures immediately, which is useful for warming images before a launch. The width and height must match the shortcode attributes, because they are part of the cache key.

Troubleshooting

Symptom Likely cause What to check
cURL error 28: Operation timed out WordPress's 5-second default timeout The timeout argument in wp_remote_post
401 Authentication failed Missing or wrong key SCREENSHOTLY_API_KEY in wp-config.php
400 Invalid request data Unknown or out-of-range field Field names and the width/height limits above
400 Unsafe URL Private, local or non-HTTP address Capture a public URL instead
403 Plan upgrade required Option needs a paid plan, for example PDF The minimumPlan field in the response
429 Rate limit exceeded Too many requests per minute, or quota used up The message field and the Retry-After header
Shortcode stays a plain link WP-Cron not running wp cron event list, or set up a system cron

Going further


Ready to add screenshots to your WordPress site?

Create a free API key →. It includes 100 captures to test with.

See also:

wordpress
php
integration
shortcodes

About the Author

Asad Ali

Asad Ali

CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.

Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients

Frequently Asked Questions

Can I trigger a screenshot automatically when a WordPress post is published?

Yes. Hook into publish_post (or transition_post_status), pick the URLs you want, and call screenshotly_queue_capture() for each one. The capture then runs in a WP-Cron event instead of making the editor wait for it.

Where should the API key live?

In a constant in wp-config.php, which keeps it out of the database, database exports and the admin screens. Never print it into page HTML or JavaScript; every request to Screenshotly in this tutorial is made by PHP on your server.

Should I use a plugin or a custom implementation?

Screenshotly does not publish a WordPress plugin. The must-use plugin in this guide is about 150 lines, stores images in your own Media Library, and is easy to audit. Use it as a starting point and adapt the caching rules to your site.

Ready to capture your first screenshot?

Get started with 100 free screenshots. No credit card required.

Related Articles