WordPressでアイキャッチがあれば表示し、なければ記事内の画像、それもなければダミー画像を表示する

WordPressでアイキャッチがあれば表示し、なければ記事内の画像、それもなければダミー画像を表示する

記事一覧などでアイキャッチ画像を表示することが多いのですが、いちいちアイキャッチを入れるのが面倒。
なのでアイキャッチ画像がなければ記事内の最初の画像を表示。それもなければダミー画像を表示。

こうしておけば見た目の体裁は整えやすいですね。

あちこちで紹介されている方法ではありますが、使う頻度が高いので記事として残しておきます。

functions.phpに画像出力に関するコードを記述します。

//アイキャッチを有効化
		add_theme_support( 'post-thumbnails' );

		//画像サイズ追加
		add_image_size('rect', 640, 400, 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, 'rect', false, array( 'class' => 'archive-thumbnail' ) );
		if( empty( $first_img ) ){
			$first_img = '<img class="attachment_post_thumbnail" src="' . get_stylesheet_directory_uri() . '/assets/img/common/no-img.jpg" alt="No image" />';
		}
		return $first_img;
		}

画像サイズに関しては640×400pxで自動トリミングありで記載していますが、既存のサイズでよければ特に記述は不要です。

出力する場所に以下のコードを記述

<?php if( has_post_thumbnail() ): ?>
			<?php echo get_the_post_thumbnail( $post->ID, 'rect', array( 'class' => 'archive-thumbnail' ) ); ?> 
		<?php else: ?>
			<?php echo catch_that_image(); ?>
		<?php endif; ?>

2行目に先ほど作成した画像サイズの「rect」を指定してます。ここは希望のサイズ(thumbnail,mediumなど)を入れてください。
またCSSで操作もしやすいよう「archive-thumbnail」というclassを付与していますが、functions.phpと合わせて任意のclass名をつけてもらえれば大丈夫です。

SPONSORED LINK

CONTACT

ご意見やご感想、お仕事のご依頼など
お気軽にご連絡ください。

CONTACT FORM