指定したURLのスクリーンショットを画像を取得し表示させるショートコード
指定したURLのスクリーンショット画像を生成するwordpressのプラグイン『BM Shots』がありますが、アクセスの度に画像取得を実行するのが嫌だったので自分のサーバに画像を保存し保存された画像を表示するようなショートコードを作成しました。
記載しているショートコードの利用は自由ですが、特にテストなど行っていないので利用される場合は、自己責任でお願いします。ショートコードの利用により生じた不具合などの責任は負いかねますので予めご了承ください。あしからず。
コード
<?php # functions.php // 指定URLのスクリーンショットを描画 function screenshotSc($atts, $content = null) { global $post; define('DS', '/'); // 画像保存ディレクトリ define('SCREENSHOT_DIR', '画像保存ディレクトリパスを記述'); extract(shortcode_atts(array( "base"=>'http://s.wordpress.com/mshots/v1/', "url" => '', "class" => 'line1', "alt" => '', "file" => '', "link" => '', "width" => '800', "height" => '533' ), $atts) ); if( empty( $url ) || empty( $file ) ) return null; /* 処理 */ $image_flag=false; $dir=SCREENSHOT_DIR; $date=$post->post_date; $year=date('Y', strtotime($date) ); $month=date('m', strtotime($date) ); $filename='http://'.$_SERVER['HTTP_HOST'].DS.'blog'.DS.'wp-content'.DS.'themes'.DS.'oniloq'.DS.'images'.DS.'screenshot'.DS.$year.DS.$month.DS.$file.'.jpg'; if( !file_exists($dir.$year) ) { mkdir($dir.$year); } if( !file_exists($dir.$year.DS.$month) ) { mkdir($dir.$year.DS.$month); } if( file_exists($dir.$year.DS.$month.DS.$file.'.jpg') ) { $image_flag=true; } if( !$image_flag ) { $url=$base.urlencode($url).'?w='.$width.'&h='.$height; $image=file_get_contents($url); file_put_contents($dir.$year.DS.$month.DS.$file.'.jpg', $image); } if( !empty($class) ) $class='class="'.$class.'"'; $img = '<img '.$class.' src="'.$filename.'" alt="' . $alt . '"/>'; if( empty($link) ) return $img; return '<p>' . '<a href="' . $link . '">' . $img . '</a>' . '</p>'; } add_shortcode("Screenshot", "screenshotSc");
記事内
記事内では下記の様なショートコードを記述する
[Screenshot url="http://google.co.jp/" file="filename" alt="google" link="http://google.co.jp"]