LoginSignup
1
0

More than 3 years have passed since last update.

【WordPress】アイキャッチ画像 ※備忘録

Posted at

はじめに

現在、WordPressの案件に携わっており、アイキャッチ画像の設定の調査をしていたので、
そのことを忘れないようにまとめてみます。

アイキャッチ画像とは?

投稿に画像を添付することができる機能。
使用するテーマによっては機能が有効化されていない場合がある。

有効化するには

function.php(wp-content/themes配下)に下記を追記する。

function.php
add_theme_support('post-thumbnails');

機能が有効化されると、管理画面の投稿編集ページの右下にアイキャッチ画像の項目が表示される。

カスタム投稿タイプでアイキャッチ画像を有効化する方法

プロパティのsupportsの値にthumbnailを追加する。

※function.phpからカスタム投稿タイプに追加した場合。

function.php
add_action( 'init', 'create_post_type' );
function create_post_type() {
  register_post_type( 'product',
    array(
      'labels' => array(
      'name' => __( 'Product' ),
      'singular_name' => __( 'Product' )
    ),
      'public' => true,
      'has_archive' => true,
      'supports' => array('title','editor','thumbnail','custom-fields','excerpt','author','trackbacks','comments','revisions','page-attributes')
    )
  );
}

アイキャッチを設定する部分に説明文を表示する方法

管理画面のアイキャッチ設定箇所に説明文(注釈的な)を追加する。

function.phpに下記を追記する。

投稿タイプ全てのアイキャッチの説明文を一気に設定する方法。

function.php
//方法1
add_filter( 'admin_post_thumbnail_html', 'add_featured_image_instruction');
function add_featured_image_instruction( $content ) {
return $content .= '<p>ここに説明文を記載します。</p>';
}

//方法2
function my_admin_post_thumbnail_html( $content ) {
  return $content .= 'ここに説明文を記載します。';
}
add_filter( 'admin_post_thumbnail_html', 'my_admin_post_thumbnail_html');

カスタム投稿ごとにアイキャッチの説明文を設定する方法

function.php
function my_admin_post_thumbnail_html( $content ) {
  $screen = get_current_screen();
  if ( $screen->post_type == 'post' ) {//投稿
    $content .= '管理画面のアイキャッチ下に説明文';
  } elseif ( $screen->post_type == 'works' ) {//カスタム投稿
    $content .= '管理画面のアイキャッチ下に説明文';
  } elseif ( $screen->post_type == 'staff' ) {//カスタム投稿
    $content .= '管理画面のアイキャッチ下に説明文';
  }
  return $content;
}
add_filter( 'admin_post_thumbnail_html', 'my_admin_post_thumbnail_html');


get_current_screen()関数を利用して、どの管理ページを見ているかを判断する

参考サイト

https://takayakondo.com/wordpress-eye-catch-text/
https://lab.studio-benkei.com/post-242/
https://developer.wordpress.org/reference/functions/get_current_screen/
https://developer.wordpress.org/reference/hooks/admin_post_thumbnail_html/
https://datalibraries.info/wordpress-admin-post-thumbnail-html/

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0