【WordPress】記事内の最初に使用されている画像のURLを取得して、要素のbackgroundイメージにする方法

記事内にある最初の画像をサムネイルにする、といったケースはよくありますが、今回はcssで指定するbackgroundイメージを、記事内の最初の画像にする方法を書きます。
要するに「background: url(ほげ);」の、「ほげ」部分に記事内の最初に使用されている画像のURLを挿入します。
functions.phpにコードを追加する
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(has_post_thumbnail()){ //アイキャッチ画像を設定している場合はアイキャッチ画像を取得
$first_img = wp_get_attachment_url( get_post_thumbnail_id() );
}
if(empty($first_img)){ //↓記事内に画像もサムネイルもない場合に表示する画像
$first_img = "/img/hoge.png";
}
return $first_img;
}
スタイルを出力
※例として「#page-title」で指定している要素の背景画像に記事内の最初の画像を挿入する場合
<style type="text/css">
#page-title{background: url(<?php echo catch_that_image(); ?>);}";
</style>
これで記事内にある最初の画像のURLが挿入されます。
最初の画像のURLが「http://a-side-job.com/img/first-hoge.png」の場合、以下のcssが出力されます。
#page-title{background: url(http://a-side-job.com/img/first-hoge.png);}”;
タグ: WordPress | 2016年7月15日



