WP-Mix

A fresh mix of code snippets and tutorials

Display WordPress Theme Screenshot

Most good themes include a screenshot, primarily to be displayed on the Themes screen in the WP Admin Area. Of course, theme screenshots can be displayed anywhere, even on the frontend.

The Trick..

The trick is using the WordPress constant, WP_CONTENT_URL, to make sure we always have the correct directory information for the theme. Here is an example that conveys the basic idea. When added to your theme template (like single.php or wherever), this snippet outputs your theme screenshot, along with the width and height in pixels.

$theme = 'name-of-theme-directory';

$file = trailingslashit(WP_CONTENT_DIR .'/themes') . trailingslashit(basename($theme)) .'screenshot.png';						

$url = trailingslashit(WP_CONTENT_URL .'/themes') . trailingslashit(basename($theme)) .'screenshot.png';

$output = '<div class="theme-info">';

if (file_exists($file)) {
	
	$image = getimagesize($file);
	
	$width  = isset($image[0]) ? $image[0] : '';
	$height = isset($image[1]) ? $image[1] : '';
	
	$output .= '<div><img src="'. $url .'" width="300" alt=""></div>';
	
	$output .= '<div>'. $width .'x'. $height .'</div>';
	
}

$output .= '</div>';

echo $output;

For this to work, your theme must include a screenshot.png file, located in the main theme directory. The only change that needs made for this example to work: edit the name-of-theme-directory in the first line. Note that should be the exact same name as the the theme directory, same casing, hyphens, or whatever: exact match.

And of course this is just a starting point for further customization and development. For example, by using a dynamic value for the $theme variable, you can display screenshots for any installed theme. I use this basic technique in my free WordPress plugin, Theme Switcha.

Enjoy!

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress