How to Generate Website Screenshots In a post in WordPress

In this tutorial, we will learn how to capture and retrieve the screenshot of any website and bring it in a WordPress post. You can be even able to use this screenshot in your WordPress posts without any plugin.
WordPress provides a screenshot generator function by which we can take the screenshot of any website by just entering the ‘URL’ of that site.
Follow these steps to generate website screenshots and show it in your blog posts.

STEP 1:- Add the following code to your functions.php file in your theme directory.

add_shortcode('ss_screenshot', 'ss_screenshot_shortcode');

function ss_screenshot_shortcode($atts){

  $width = intval($atts['width']);

  $width = (100 <= $width && $width <= 300) ? $width : 200;

  $site = trim($atts['site']);

  if ($site != ''){

    $query_url =  'http://s.wordpress.com/mshots/v1/' . urlencode($site) . '?w=' . $width;

    $image_tag = '<img class="ss_screenshot_img" alt="' . $site . '" width="' . $width . '" src="' . $query_url . '" />';

    echo '<a class="ss_screenshot_link" href = "' . $site . '">' . $image_tag . '</a>'; 

  }else{

    echo 'Bad screenshot URL!';

  }
}

Now let me give you some description about this code

  • This function declares a shortcode called ss_screenshot. the shortcode function accepts the $atts array containing the two shortcode attributes: width and site.
  • The ‘site’ attribute is trimmed to remove accidental left and right spaces
  •  Create a query URL by adding a urlencoded site attribute and the width attribute
  •  Finally, we wrap the query_url in an image tag and a link tag so that users can click the screenshot and be taken to the site.

STEP 2:-  Use this shortcode in your page or post and you’ll surely find a screenshot on your blog/page.

[ss_screenshot width='300' site='https://smallenvelop.com']

Here you can change site URL and width attribute.

STEP3:-  If you want to display a screenshot of a website within each of you blog post, you can use this function with a custom field.So make a custom field with name ‘screenshot_url’ within your page.

Don’t worry if you not finding custom field option in your post edit screen. then look at screen top right and you should see the Screen Options tab. Click that and tick the Custom Fields box.

generate website screenshots

Now you should see something like this at screen bottom:

custom field option

STEP4:- Now we put our shortcode within WordPress loop.

if (have_posts()) while (have_posts()) : the_post();

  the_title();

  $url = get_post_meta($post->ID, 'screenshot_url', true);

  do_shortcode('[ss_screenshot width="280" site="' . $url . '"]'); 

  the_content();

endif;
endwhile;

STEP5:- Now you can see that a screenshot of the URL which we entered in the custom field value appears  within  our post.

post with screenshot

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.