wordpressのアイキャッチ画像の設定についてまとめてみました。

アイキャッチの利用設定

functions.phpに記載

add_theme_support( 'post-thumbnails' );

アイキャッチを挿入したい場所に下記のいずれかのソースを記載。


<?php the_post_thumbnail("thumbnail"); ?> // サムネイル画像を表示 
<?php the_post_thumbnail("medium"); ?> // 中サイズ画像を表示 
<?php the_post_thumbnail("large"); ?> // 大サイズ画像を表示 
<?php the_post_thumbnail(array(100, 50)); ?> // 横・縦指定(数値は任意で変更可) 
<?php the_post_thumbnail("post-thumbnail"); ?> // アイキャッチ画像を表示 
<?php the_post_thumbnail(); ?> // アイキャッチ画像を表示(上と同じ)

画像アップロードで作成される画像の種類を追加する

functions.phpにadd_image_sizeを追記

下記は、横430px、縦320pxの gallery_large というサイズと、横203px、縦149pxの gallery_small というサイズを追加する記述例。


add_image_size( 'gallery_large', 430, 320, true ); add_image_size( 'gallery_small', 203, 149, true );

アイキャッチで出力されるimgタグ中のサイズやクラスを変更

functions.php へ以下のように記入する

クラス名を削除する


add_filter( 'post_thumbnail_html', 'custom_attribute' );
function custom_attribute( $html ){
    // class を削除する
    $html = preg_replace('/class=".*\w+"\s/', '', $html);
    return $html;
}

サイズ指定を削除する


add_filter( 'post_thumbnail_html', 'custom_attribute' );
function custom_attribute( $html ){
    // width height を削除する
    $html = preg_replace('/(width|height)="\d*"\s/', '', $html);
    return $html;
}

メディア挿入時の添付ファイルの表示設定の配置を「なし」にする


function media_script_buffer_start() {
    ob_start();
}
add_action( 'post-upload-ui', 'media_script_buffer_start' );
function media_script_buffer_get() {
    $scripts = preg_replace( '#<option value="file" selected>.*?<option>#s', '', $scripts );
    echo $scripts;
}
add_action( 'print_media_templates', 'media_script_buffer_get' );

前の記事 次の記事