このブログはFacebookとTwitterに自動投稿し、ときどきGoogle+にも手動で投稿しています。
そろそろ記事特有の画像を使いたいと思い、「記事の1枚目の画像か、OGP画像のデフォルトの画像を取得する」方法を調べてみました!
function.phpで記事の1枚目の画像か、OGP画像のデフォルトの画像を取得する
※以前載せていたWordPress(ワードプレス)で記事の一番最初の画像を取得する方法 | 株式会社LIGのコードだと取得できなくなっていたので、新しいものに書き換えました。
function catch_that_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches [1] [0]; if(empty($first_img)){ //Defines a default image $first_img = デフォルトの画像パス } return $first_img; }
取得した画像をheader.phpで呼び出す
<meta property="og:image" content="<?php echo catch_that_image(); ?>">
参考サイト:構想雑文 : [Wordpress]投稿記事から画像を取得し、リサイズして画像を画像を表示させるには – livedoor Blog(ブログ)