【WordPress】固定ページのカスタムHTMLブロックの表示サイズを変更する

WordPressの固定ページの「カスタムHTML」ブロックの高さをコンテンツの長さによって変更する

スポンサードサーチ

準備

「globa $post_type 」を取得。固定ページのみ読み込むようにする。functions.phpに下記を記述する。

jsファイルは、「wp-content/themes/テーマ名/assets/js」に入っているものとする。

function admin_post_type() {
    global $post_type;
    $tmp_js_url = get_template_directory_uri() . '/assets/js/';
    if($post_type === 'page'){
        wp_enqueue_script(
          'custom_html',$tmp_js_url . 'custom.js',false,false,false
        );
      }
  }
  add_action( 'admin_enqueue_scripts', 'admin_post_type', 10, 2 );

Javascript パターン1

  • カスタムHTMLブロック(コンテンツ)のheightを取得。
  • カスタムHTMLブロックのmax-heightは250px。
  • 取得したコンテンツのheightがそれ以上であれば、コンテンツのmax-heightを変更し、表示範囲を増やす
  • 複数使用する場合も考えられるため、forEachで全てのカスタムHTMLブロックを取得しておく。
  • 画面クリックで発火する
window.addEventListener("click", () => {
  customHtmlSize();
});

function customHtmlSize() {
  const textArea = document.querySelectorAll(
    "textarea.block-editor-plain-text"
  );

  textArea.forEach((el) => {
    const h = parseInt(el.style.height);
    if (Number.isInteger(h)) {
      if (h > 250) {
        el.style.maxHeight = `${h}px`;
      }
    }
  });
}

スポンサードサーチ

JavaScript パターン2

  • カスタムHTMLブロック(コンテンツ)の高さを取得、max-heightを変更するのはパターン1と同じ。
  • ブロックをクリックして、.block-editor-plain-textを持っていれば発火。
window.addEventListener('DOMContentLoaded', () => {
  customHtmlSize ();
})

function customHtmlSize () {
  window.addEventListener('click' , (e) => {
    const target = e.target;
    if(!target.classList.contains('block-editor-plain-text')) return;

    const h = parseInt(target.style.height);
    if (h > 250) {
      target.style.maxHeight = `${h}px`;
    }
  });
}

おわりに

あまり使うことはないと思うけど、メモとして残しておく。