はじめに
外観 →メニューでは、テーマが用意したメニュー位置だけでなく、独自のメニュー表示位置を追加することもできます。
そこで、独自のメニュー位置を登録し、設定したメニューをフロント側に反映します。
この記事では、この方法について説明します。
完成イメージ


実装手順
以下の手順で実装します。
- ラベルPHPを追加
以下のコードをfunctions.phpに追加します。
// メニューの位置を追加 add_action('init', function () { register_nav_menu('follow-menu', 'フローティングメニュー'); }); // ページ下部にフローティングメニューを出力 add_action('wp_footer', function () { if (!has_nav_menu('follow-menu')) { return; } ?> <input type="checkbox" id="follow-menu-toggle"> <div class="follow-menu"> <label for="follow-menu-toggle" class="follow-menu__label">MENU</label> <?php wp_nav_menu([ 'theme_location' => 'follow-menu', 'container' => 'nav', 'depth' => 1, ]); ?> </div> <?php }); - ラベルCSSを追加
以下のコードをstyle.cssに追加します。
/* チェックボックス */ #follow-menu-toggle { display: none; &:checked + .follow-menu { right: 0; } } /* コンテナ */ .follow-menu { --width: 200px; display: flex; filter: drop-shadow(-1px 1px 2px rgba(0, 0, 0, 0.2)); position: fixed; right: calc(var(--width) * -1); top: 50%; transform: translateY(-50%); transition: right 0.5s ease-in-out; z-index: 999999; .follow-menu__label { background-color: #1e73be; border-radius: 10px 0 0 10px; color: #fff; cursor: pointer; line-height: 40px; text-align: center; writing-mode: vertical-rl; } ul { background-color: #333; display: flex; flex-direction: column; gap: 5px; list-style: none; margin: 0; padding: 10px; width: var(--width); } a { color: #fff; display: block; text-decoration: none; } }
さいごに
今回紹介した方法を使えば、WordPress標準のメニュー位置に依存せず、自由な場所にメニューを表示できるようになります。
UI改善にも応用しやすいので、ぜひ活用してみてください。
