Fetch and Display Website Screenshots with a Snippet

By WebCare in December 26, 2024 – Reading time 4 minute

This tutorial will show you how to automatically fetch, save, resize, and display website screenshots for any website, directly in your posts or pages using a snippet. Let’s dive in!

What Does the Snippet Do?

The snippet allow you to:

  1. Automatically fetch a full-page screenshot of any website using the ScreenshotOne API.
  2. Save the screenshot in your WordPress uploads folder
  3. Dynamically resize or crop the screenshot to various sizes (e.g., small, medium, full) to fit your content.
  4. Display the screenshot in WordPress using a shortcode, making it easy to show the image anywhere on your site.

Before we dive into the code, make sure you’ve registered for the ScreenshotOne API and have your API key ready. Visit ScreenshotOne Documentation, then sign up and obtain your access key.

Overview Steps

Step 1 – Creating the Snippet

First, we’ll create a custom WordPress shortcode to handle the screenshot fetching and displaying. Here’s how to set it up:

function check_and_display_screenshot($atts) {
    $atts = shortcode_atts(
        array(
            'url' => '',
            'size' => 'full', // Allowed values: 'full', 'medium', 'small'
        ),
        $atts
    );

    $website_url = $atts['url'];
    $size = $atts['size'];

    if (!$website_url) {
        return 'Website URL is missing.';
    }

    $website_name = parse_url($website_url, PHP_URL_HOST);
    $upload_dir = wp_upload_dir();
    $screenshot_file = $upload_dir['basedir'] . '/screenshot-web/' . sanitize_file_name($website_name) . '-full.webp';

    // Check if screenshot exists; if not, fetch it
    if (!file_exists($screenshot_file)) {
        fetch_screenshot($screenshot_file, $website_url);
    }

    // Generate the required size on the fly
    $image_tag = generate_screenshot_size($screenshot_file, $size, $website_name);

    return $image_tag;
}
add_shortcode('website_screenshot', 'check_and_display_screenshot');

This function will:

  • Fetches a screenshot using fetch_screenshot() if it doesn’t already exist.
  • Calls generate_screenshot_size() to create the requested size dynamically.

Next, we create a function that will generate resized versions of the screenshot with desired aspect ratio and returns it as a Base64-encoded <img> tag.

function generate_screenshot_size($original_file, $size, $website_name) {
    $original_image = imagecreatefromwebp($original_file);
    if (!$original_image) {
        return 'Failed to process the original screenshot.';
    }

    $original_width = imagesx($original_image);
    $original_height = imagesy($original_image);

    // Define target sizes
    $dimensions = array(
		'full' => array('width' => $width, 'height' => $height), // No change, full original size
        'medium' => array('width' => 1280, 'height' => 720), // 16:9
        'small' => array('width' => 720, 'height' => 540),   // 4:3
    );

    // Validate size and fallback to 'full'
    if (!isset($dimensions[$size])) {
        $size = 'full';
    }
	
	if ($size == 'full') {
        ob_start();
        imagewebp($original_image);
        $image_data = ob_get_clean();
        $base64_image = 'data:image/webp;base64,' . base64_encode($image_data);
        return '<img src="' . $base64_image . '" alt="' . esc_attr($website_name . ' - Full Screenshot') . '" class="screenshot-full">';
    }

    $target_width = $dimensions[$size]['width'];
    $target_height = $dimensions[$size]['height'];

    // Calculate the resized height to maintain the original aspect ratio
    $resized_height = (int) ($target_width / $original_width * $original_height);

    // Create a temporary image with the target width and resized height
    $temp_image = imagecreatetruecolor($target_width, $resized_height);
    imagecopyresampled(
        $temp_image,
        $original_image,
        0, 0,
        0, 0,
        $target_width, $resized_height,
        $original_width, $original_height
    );

    // If the resized height exceeds the target height, crop the excess from the bottom
    $final_image = imagecreatetruecolor($target_width, $target_height);
    imagecopy(
        $final_image,
        $temp_image,
        0, 0, // Destination (0,0)
        0, 0, // Source (top-left corner)
        $target_width, $target_height
    );

    ob_start();
    imagewebp($final_image);
    $image_data = ob_get_clean();

    imagedestroy($original_image);
    imagedestroy($temp_image);
    imagedestroy($final_image);

    $base64_image = 'data:image/webp;base64,' . base64_encode($image_data);

    return '<img src="' . $base64_image . '" alt="' . esc_attr($website_name . ' - ' . ucfirst($size) . ' Screenshot') . '" class="screenshot-' . esc_attr($size) . '">';
}

Then, create a function that will fetch the screenshot using the ScreenshotOne API with various parameters and stores it locally in the specified folder.

function fetch_screenshot($file_path, $website_url) {
    $screenshotone_api_key = 'YOUR_API_KEY_HERE';
    $api_url = 'https://api.screenshotone.com/take?access_key=' . $screenshotone_api_key . 
        '&url=' . urlencode($website_url) . 
        '&full_page=true' . 
        '&full_page_scroll=true' .
        '&viewport_width=1920' . 
        '&viewport_height=1080' . 
        '&device_scale_factor=1' . 
        '&format=webp' . 
        '&image_quality=80' . 
        '&block_ads=true' . 
        '&block_cookie_banners=true' . 
        '&block_banners_by_heuristics=true' . 
        '&block_trackers=true' . 
        '&wait_until=load' . 
        '&wait_until=domcontentloaded' . 
        '&reduced_motion=true' .
		'&timeout=90';

    $screenshot_data = file_get_contents($api_url);
    if ($screenshot_data === false) {
        return false;
    }

    file_put_contents($file_path, $screenshot_data);
    return true;
}

Step 2 – Set Your ScreenshotOne API Key

In the fetch_screenshot() function, replace 'YOUR_API_KEY_HERE' with your ScreenshotOne API key. You can obtain the access key here.

Step 3 – Configure the Screenshot Folder

Make sure the /wp-content/uploads/screenshot-web/ directory exists and is writable. The snippet will store screenshots here.

Step 4 – Use the Shortcodes

Lastly, use the [website_screenshot] shortcode with the desired website URL and size to fetch and display the screenshot. Example:

[website_screenshot url="https://example.com" size="medium"]

Available sizes:

  • Full: Original screenshot size. (Full page)
  • Medium: 1280×720 resolution (16:9 ratio).
  • Small: 720×540 resolution (4:3 ratio).

Conclusion

This method can be used to display any desired website screenshots, which are perfect for product reviews, or case studies on your WordPress site.

You Made It to the End!🔥
Free Tips in Your Inbox
Get the latest, evergreen tips to secure, quicken and improve your WordPress in our weekly newsletter.
No spam policy, pure value tips/ tricks
Subscription Form

Written by