アイキャッチ画像を有効にする|WordPressテーマ作成

テーマ作成でアイキャッチ画像を有効にする方法です。

アイキャッチ画像設定無効

投稿画面にアイキャッチ画像の設定がありません

functions.php

設定項目の有効化

functions.phpに下記を記述します。

if ( function_exists( 'add_theme_support' ) ) {
	// Enable eyecatch image.
	add_theme_support( 'post-thumbnails' );
}
アイキャッチ画像設定有効

投稿画面にアイキャッチ画像の設定が表示されました

サムネイルサイズの追加

一覧画面用などに独自のサムネイルサイズを設定したい場合は下記を記述します。

if ( function_exists( 'add_image_size' ) ) {
	add_image_size( 'add-thumb200', 200, 200, true );
}

add-thumb200という名前でサイズ200x200のサムネイルを追加しました。第4引数は切り抜きモード指定サイズにCropする(true)かアスペクト比維持で縮小する(false)かになります。

サムネイル画像の取得

index.phpなどでthe_post_thumbnail()をコールして取得します。

サンプル

<?php if ( has_post_thumbnail( $post->ID ) ): ?>
    <?php the_post_thumbnail( 'add-thumb200' ); ?>
<?php else: ?>
    <img width="200" height="200" src="noimg.png" alt="no image" />
<?php endif; ?>
サムネイル表示サンプル

投稿一覧にもサムネイルを表示する

投稿一覧にもサムネイルを表示したい場合のサンプルです。ここではサイズ100x100のサムネイルを表示しています。

サンプル

/* Add columns on post list screen. */
if ( !function_exists( 'add_posts_columns' ) ) {
	function add_posts_columns( $columns ) {
		$columns['thumbnail'] = 'サムネイル';
		return $columns;
	}
}

/* Puts HTML for custom column. */
if ( !function_exists( 'puts_posts_custom_column' ) ) {
	function puts_posts_custom_column( $column_name, $post_id ) {
		if ( 'thumbnail' === $column_name ) {
			$thumbnail = get_the_post_thumbnail( $post_id, array( 100, 100 ) );
			echo ( empty( $thumbnail ) ) ? '' : $thumbnail;
		}
	}
}

add_filter( 'manage_posts_columns', 'add_posts_columns' );
add_action( 'manage_posts_custom_column', 'puts_posts_custom_column', 10, 2 );
投稿一覧サムネイル
このエントリーをはてなブックマークに追加
にほんブログ村 IT技術ブログへ

スポンサードリンク

関連コンテンツ

コメント

メールアドレスが公開されることはありません。 が付いている欄は必須項目です