WordPressで記事内の最初の画像を取得して表示させるコード
注:この記述は記事に張り付けてある画像の大きさそのままを取得します
◆function.php内に以下を記述
※コード内の「default.jpg」は記事内に画像が無い場合に表示する代替え画像
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all("/<img[^>]+src=[\"'](s?https?:\/\/[\-_\.!~\*'()a-z0-9;\/\?:@&=\+\$,%#]+\.(jpg|jpeg|png|gif))[\"'][^>]+>/i", $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "default.jpg";
}
return $first_img;
}
◆テンプレート内に以下を記述
<img src="<?php echo catch_that_image(); ?>">
記事内の最初の画像を取得してサムネイルを表示させるコード
注:この記述は記事に張り付けてある画像のサムネイルを取得します
function.phpに以下を記述
/画像サイズをセット
set_post_thumbnail_size( 150, 150, true );
//画像URLからIDを取得
function get_attachment_id_by_url( $url ) {
global $wpdb;
$sql = "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s";
preg_match( '/([^\/]+?)(-e\d+)?(-\d+x\d+)?(\.\w+)?$/', $url, $matches );
$post_name = $matches[1];
return ( int )$wpdb->get_var( $wpdb->prepare( $sql, $post_name ) );
}
//画像をサムネイルで出力
function catch_that_image() {
global $post;
$first_img = '';
$output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches );
$first_img_src = $matches[1][0];
$attachment_id = get_attachment_id_by_url( $first_img_src );
$first_img = wp_get_attachment_image( $attachment_id, 'thumbnail', false, array( 'class' => 'archive-thumbnail' ) );
if( empty( $first_img ) ){
$first_img = '<img class="attachment_post_thumbnail" src="' . get_stylesheet_directory_uri() . '/images/no_image.png" alt="No image" />';
}
return $first_img;
}
テンプレート内に以下を記述
※アイキャッチ画像があるときはそちらを表示
<?php if( has_post_thumbnail() ): ?> <?php echo get_the_post_thumbnail( $post->ID, 'thumbnail', array( 'class' => 'archive-thumbnail' ) ); ?> <?php else: ?> <?php echo catch_that_image(); ?> <?php endif; ?>