Last active
September 29, 2015 05:10
-
-
Save Ikaring/4da8dedf45b9a08e0c16 to your computer and use it in GitHub Desktop.
アイキャッチ画像がないときに記事内の最初の画像からサムネイルを取得する[WordPress]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//ループ内で使用 | |
//アイキャッチ画像を$thumbに格納 | |
if( has_post_thumbnail() ) { | |
//アイキャッチ画像が設定されているとき | |
$thumb = get_the_post_thumbnail( $post->ID, 'thumbnail' ); | |
} else { | |
//記事に配置した画像にはwp-image-{id}というクラスが付くのを利用して記事に画像があるかどうか判断 | |
preg_match('/wp-image-(\d+)/i' , $post->post_content, $thumbs); | |
if( empty( $thumbs ) ){ | |
//記事に画像がない場合ダミー画像を配置 | |
$thumb = '<img src="' . get_stylesheet_directory_uri(). '/images/blog/bn_blog.png" alt="Hanao Bridal Classical Style"/>'; | |
} else { | |
//アイキャッチ画像が設定されていない場合に記事の最初の画像を表示する。 | |
$thumb = wp_get_attachment_image($thumbs[1], 'thumbnail'); | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment