【WordPress】ブロックエディターで自作ツリービューをプラグイン無しで作成しよう

フォルダ階層をひと目で把握できるツリービューを、HTMLとCSSののみで実装します。WordPressのブロックエディターで簡単に利用できるように、リストブロックのブロックスタイルとして登録します。

完成形はこちらです。

  • themes
    • parentーtheme
      • functions.php
      • style.css
    • child-theme
      • functions.php
      • style.css
    • index.php

WordPressのブロックエディターにツリービューを実装する手順

functions.phpを編集

子テーマのfunctions.phpに下記コードを追記し、リストブロックのブロックスタイルを登録する。

function my_customize_block_style(){
	// リスト:ツリービュー
	register_block_style(
		'core/list',
		array(
			'name' => 'list-style-tree-view',
			'label' => 'ツリービュー',
		)
	);
add_action('init', 'my_customize_block_style');

style.cssを編集

WordPressサイトの場合は、子テーマを有効にしているなら子テーマのstyle.cssに、子テーマがないなら追加CSSに記述する。

.wp-block-list.is-style-list-style-tree-view {
	list-style-type: none;
	padding: 20px 30px;
	background-color: #2d2d2d;
	color: #ccc;
}

.wp-block-list.is-style-list-style-tree-view ul{
	position: relative;
	margin: 0;
	margin-left: 30px;
	padding: 0;
	list-style-type: none;
}
.wp-block-list.is-style-list-style-tree-view ul:before {
	content: "";
	display: block;
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	border-left: 1px solid #ccc;
}
.wp-block-list.is-style-list-style-tree-view ul li {
	position: relative;
	margin: 0;
	padding: 5px 25px;
}
.wp-block-list.is-style-list-style-tree-view ul li:before {
	content: "";
	display: block;
	position: absolute;
	top: 15px;
	left: 0;
	width: 15px;
	border-top: 1px solid #ccc;
}
.wp-block-list.is-style-list-style-tree-view ul li:last-child:before {
	top: 15px;
	bottom: 0;
	height: auto;
	background-color: #2d2d2d;
}

ツリービューの基本的な使い方

ブロックエディタにリストブロックを挿入し、親の<ul>を選択した状態で、右パネルのブロックスタイルツリービューのボタンをクリックすると、あらかじめ設定したスタイルが適用されます。

  • themes
    • parentーtheme
      • functions.php
      • style.css
    • child-theme
      • functions.php
      • style.css
    • index.php

ツリービューのカスタマイズ

作成したツリービューは、エディター機能でフォントカラーを指定したり、文字の大きさを自由に変更することができます。

また、ツリー図の階層の深さに制限はありません。

技術ブログにツリービューを使おう

技術ブログではフォルダ操作やディレクトリ構成の説明はつきものです。複雑な階層構造がひと目でわかるツリービューを活用して、未来の自分が振り返ったときにすんなりと理解できるようにしておきたいですね。