投稿一覧にアイキャッチ画像の設定・削除機能を追加する方法

Cocoonカスタマイズ集
この記事は約12分で読めます。
記事内に広告が含まれています。

はじめに

WordPressでは、投稿や固定ページのアイキャッチ画像を設定・変更する場合、通常は編集画面を開く必要があります。
記事数が多い場合、投稿ごとに編集画面を開いて操作するのは手間がかかります。

Cocoonでは、Cocoon設定→管理者画面→カラム表示「アイキャッチを表示する」を有効にすると、投稿一覧にアイキャッチ画像を表示できます。

そこで、投稿一覧からアイキャッチ画像を追加・削除できる機能を実装します。
編集画面を開くことなく、一覧画面から直接アイキャッチ画像を管理できるようになります。

この記事では、この方法について説明します。

完成イメージ

実装手順

以下のコードをfunctions.phpに追加します。

// 管理画面用JS・CSSを追加
add_action('admin_enqueue_scripts', function ($hook_suffix) {
  if ($hook_suffix !== 'edit.php') {
    return;
  }

  // 現在の画面情報を取得
  $screen = get_current_screen();
  if (!$screen || !in_array($screen->post_type, ['post', 'page'], true)) {
    return;
  }

  ob_start();
  ?>
  .my-featured-image-button {
    align-items: center;
    background: 0 0;
    border: 1px solid #ccc;
    color: var(--wp-admin-theme-color-darker-20);
    cursor: pointer;
    font-size: 11px;
    height: 75px;
    overflow: hidden;
    padding: 0;
    width: 75px;
  }

  .my-featured-image-button img {
    display: block;
    height: 100% !important;
    object-fit: cover;
    width: 100% !important;
  }

  .my-featured-image-button:hover {
    background: rgba(var(--wp-admin-theme-color--rgb),.04);
    color: var(--wp-admin-theme-color-darker-20);
  }

  .my-featured-image-button:disabled {
    cursor: wait;
    opacity: 0.5;
  }

  .my-featured-image-delete {
    min-width: 75px;
    text-align: center;
  }
  <?php
  wp_add_inline_style('wp-admin', ob_get_clean());

  wp_enqueue_media();

  $handle = 'my-thumbnail-admin';
  wp_register_script($handle, '', ['jquery', 'media-editor'], false, true);
  wp_enqueue_script($handle);

  wp_localize_script($handle, 'myCocoonThumbnailData', [
    'ajaxurl' => admin_url('admin-ajax.php'),
    'cocoon_thumbnail_nonce' => wp_create_nonce('cocoon_thumbnail_action'),
  ]);

  ob_start();
  ?>
  jQuery(function($) {
    var data = myCocoonThumbnailData;

    /**
     * アイキャッチ設定ボタンを生成
     *
     * @param {jQuery} $cell 対象のカラム
     * @param {string} imageHtml アイキャッチ画像のHTML
     * @return {void}
     */
    function render($cell, imageHtml) {
      // 既存の設定ボタンを取得
      var $set = $cell.find('.my-featured-image-button');

      // 設定ボタンがなければ生成
      if (!$set.length) {
        $set = $('<button type="button" class="my-featured-image-button" title="アイキャッチ画像を設定">');
        $cell.empty().append($set);
      }

      // ボタンの無効状態と表示内容を変更
      $set.prop('disabled', false).html(imageHtml || '画像を設定');

      // 既存の削除ボタンを削除
      $cell.find('.my-featured-image-delete').remove();

      // 画像がある場合は削除ボタンを追加
      if (imageHtml) {
        $cell.append('<button type="button" class="button button-small my-featured-image-delete" title="アイキャッチ画像を削除">削除</button>');
      }
    }

    // アイキャッチ列を初期化
    $('.wp-list-table td.column-thumbnail').each(function() {
      var $cell = $(this);

      // 行のIDから投稿IDを取得
      var match = ($cell.closest('tr').attr('id') || '').match(/^post-(\d+)$/);

      // 投稿IDを取得できない行は処理対象外
      if (!match) {
        return;
      }

      // 投稿IDをセルに登録
      $cell.data('post-id', match[1]);

      // 既存の画像HTMLを取得して表示を変更
      render($cell, $cell.find('img').first().prop('outerHTML') || '');
    });

    // アイキャッチ画像を設定
    $(document).on('click', '.my-featured-image-button', function() {
      var $button = $(this);
      var $cell = $button.closest('td');
      var postId = $cell.data('post-id');

      // 投稿IDがない場合や通信中は処理を終了
      if (!postId || $button.prop('disabled')) {
        return;
      }

      // メディアライブラリを生成
      var frame = wp.media({
        title: 'アイキャッチ画像を選択',
        button: { text: 'この画像を設定' },
        library: { type: 'image' },
        multiple: false
      });

      // 選択した画像の情報を取得
      frame.on('select', function() {
        var attachment = frame.state().get('selection').first().toJSON();

        // 二重送信を防ぐためボタンを無効化
        $button.prop('disabled', true);

        // アイキャッチ画像の保存をリクエスト
        $.post(data.ajaxurl, {
          action: 'cocoon_set_thumbnail',
          cocoon_thumbnail_nonce: data.cocoon_thumbnail_nonce,
          post_id: postId,
          attachment_id: attachment.id
        }).done(function(res) {
          if (res.success) {
            // 保存した画像HTMLで表示を変更
            render($cell, res.data);
          } else {
            // 保存失敗時にボタンの無効状態を解除
            $button.prop('disabled', false);
          }
        }).fail(function() {
          // 通信失敗時にボタンの無効状態を解除
          $button.prop('disabled', false);
        });
      });

      // メディアライブラリを表示
      frame.open();
    });

    // アイキャッチ画像を削除
    $(document).on('click', '.my-featured-image-delete', function() {
      var $button = $(this);
      var $cell = $button.closest('td');
      var postId = $cell.data('post-id');

      // 投稿IDがない場合や通信中、確認キャンセル時は処理を終了
      if (!postId || $button.prop('disabled') || !confirm('アイキャッチ画像を削除しますか?')) {
        return;
      }

      // 二重送信を防ぐためボタンを無効化
      $button.prop('disabled', true);

      // アイキャッチ画像の削除をリクエスト
      $.post(data.ajaxurl, {
        action: 'cocoon_delete_thumbnail',
        cocoon_thumbnail_nonce: data.cocoon_thumbnail_nonce,
        post_id: postId
      }).done(function(res) {
        if (res.success) {
          // 未設定の表示に変更
          render($cell, '');
        } else {
          // 削除失敗時にボタンの無効状態を解除
          $button.prop('disabled', false);
        }
      }).fail(function() {
        // 通信失敗時にボタンの無効状態を解除
        $button.prop('disabled', false);
      });
    });
  });
  <?php
  wp_add_inline_script($handle, ob_get_clean());
});


// Ajaxアクションを追加(画像を保存)
add_action('wp_ajax_cocoon_set_thumbnail', function () {
  // nonceチェック
  check_ajax_referer('cocoon_thumbnail_action', 'cocoon_thumbnail_nonce');

  // 投稿IDと添付ファイルIDを取得
  $post_id       = isset($_POST['post_id']) ? absint(wp_unslash($_POST['post_id'])) : 0;
  $attachment_id = isset($_POST['attachment_id']) ? absint(wp_unslash($_POST['attachment_id'])) : 0;

  // 投稿IDと権限チェック
  if (!$post_id || !current_user_can('edit_post', $post_id)) {
    wp_send_json_error();
  }

  // 投稿タイプを検証
  if (!in_array(get_post_type($post_id), ['post', 'page'], true)) {
    wp_send_json_error();
  }

  // 添付ファイルが画像であることを検証
  if (
    !$attachment_id ||
    get_post_type($attachment_id) !== 'attachment' ||
    !wp_attachment_is_image($attachment_id)
  ) {
    wp_send_json_error();
  }

  // アイキャッチ画像を設定
  set_post_thumbnail($post_id, $attachment_id);

  // Cocoonと同じサイズで画像HTMLを取得
  $html = get_the_post_thumbnail($post_id, THUMB150);

  // 画像HTMLがあれば成功、なければ失敗を返却
  $html ? wp_send_json_success($html) : wp_send_json_error();
});


// Ajaxアクションを追加(画像を削除)
add_action('wp_ajax_cocoon_delete_thumbnail', function () {
  // nonceチェック
  check_ajax_referer('cocoon_thumbnail_action', 'cocoon_thumbnail_nonce');

  // 投稿IDを取得
  $post_id = isset($_POST['post_id']) ? absint(wp_unslash($_POST['post_id'])) : 0;

  // 投稿IDと権限チェック
  if (!$post_id || !current_user_can('edit_post', $post_id)) {
    wp_send_json_error();
  }

  // 投稿タイプを検証
  if (!in_array(get_post_type($post_id), ['post', 'page'], true)) {
    wp_send_json_error();
  }

  // アイキャッチ画像を削除
  delete_post_thumbnail($post_id);

  wp_send_json_success();
});

さいごに

今回紹介した方法を使えば、WordPressの投稿一覧からアイキャッチ画像を直接設定・変更・削除できるようになります。
メディアライブラリから画像を選択して保存したり、確認ダイアログを表示して削除したりできるため、投稿や固定ページの編集画面を開く手間を省けます。
投稿一覧からアイキャッチ画像をまとめて管理したい場合に、便利なカスタマイズです。

タイトルとURLをコピーしました