[WordPress] URLを指定してサイトのスクリーンショットを表示するショートコード(WordPress.comのAPIを使用)

最近WordPressをあれこれいじってみている@kasumiiです。こんにちは。

WordPressのショートコードを使っていろいろ便利にしてみたいなー。ということで、

[[wpshot url="http://wordpress.com/"]]

のようにURLを渡すだけで以下のようなリンク付きのスクリーンショットを表示してくれるものを作ってみました。

スクリーンショットの表示にはWordPress.comのAPIを使用しています。

[wpshot url=”http://wordpress.com/” width=”300″]

functions.phpに以下のコードをコピーします。

// WordPress APIでスクリーンショットを表示するショートコード
function get_wp_screenshot($attr) {
	extract(shortcode_atts(array(
		// デフォルト設定
		'url' => '',
		'alt'  => '',
		'class' => '', // imgタグに付加するclass名
		'width' => 0, // 画像の幅(0の場合はwidthタグを出力しない)
		'link' => 1 // 0:リンクしない 1:リンクする
	), $attr));
	if ($url == '') {
		return;
	}
	$image = 'http://s.wordpress.com/mshots/v1/' . urlencode(clean_url($url));
	if ($width > 0) {
		$height = floor($width/4*3);
		$image .= '?w=' . $width;
		$image_wh = ' width="' . $width . '" height="' . $height . '"';
	}
	if ($class != '') {
		$image_wh .= ' class="' . $class . '"';
	}
	$image = '<img src="' . $image . '" alt="' . $alt . '"' . $image_wh . '>';
	if ($link == 1) {
		$image = '<a href="' . $url . '" target="_blank">' . $image . '</a>';
	}
	return $image;
}
add_shortcode('wpshot','get_wp_screenshot');

投稿記事の中で、以下のようにショートコードを書けばスクリーンショットが表示されます。

[[wpshot url="スクリーンショットを撮るURL" width="幅" alt="説明" class="クラス名"]]

URL以外のパラメーターは省略できます。

WordPress.com APIで取得したスクリーンショットは常に横4 : 縦3の比率になります。

たとえばwidth="400"とした場合は、幅400px 高さ300px の画像が表示されます。(高さは幅に合わせて自動で設定)

[[wpshot url="http://wordpress.com/" link="0"]]

link="0"をつければ、こんな感じでリンクタグなしの画像だけを表示することができます。

[wpshot url=”http://wordpress.com/” width=”300″ link=”0″]
[[wpshot url="http://wordpress.com/" width="0"]]

レスポンシブなレイアウトにしたい場合など、画像の幅や高さをCSS側で制御したいときはwidth="0"と書くことでimgタグのwidthとheightを出力しないように設定できます。

ショートコードにしておけばもしWordPress.comのAPIが使えなくなってスクリーンショット取得できなくなったときでも、他のサービスにすぐ切り替えられるから良さそうですね。

【参考】URLだけでサイトのスクリーンショットを取得して簡単にサムネイル画像がつくれるサービスやAPIを調べてみた