Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPBカップ
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

WordPressのメニュー項目に最初と最後のCSSクラスを追加する方法

編集メモ: WPBeginner のパートナーリンクから手数料を得ています。手数料は編集者の意見や評価に影響を与えません。編集プロセスについて詳しく知る。

WordPressメニューの最初と最後の項目にカスタマイザーを追加したいですか?

1つのオプションは、単に最初と最後のメニュー項目にカスタムCSSクラスを追加することです。しかし、メニューを並べ替えた場合、それらの項目が最初と最後でなくなる可能性があります。

この投稿では、.firstと.lastクラスを追加する方法を紹介します。このクラスは、メニューの順番を後から変更した場合でも、最初と最後の項目にスタイルを適用します。

How to Add the First & Last Class to WordPress Navigation Menu Items

なぜ最初と最後のナビゲーション項目でスタイルを変えるのか?

ナビゲーションメニューの最初と最後の項目にカスタマイザーを追加する必要がある場合があります。これにより、サイトのお問い合わせフォームやお買い物カゴページへのリンクなど、重要なリンクを目立たせることができます。

この場合、最初と最後のメニュー項目にカスタムCSSクラスを追加するだけでよい。しかし、メニューの順序を変更すると、カスタマイザーが完全に壊れてしまう可能性があります。

そのため、フィルターの使用をお勧めします。

このガイドでは、ナビゲーション・メニューの最初と最後の項目にスタイルを設定する方法を説明します。以下のクイックリンクから、お好きな方法にジャンプしてください:

方法1:フィルターを使用して最初と最後のクラスを追加する(推奨)

注: この方法はクラシックWordPressテーマでのみ機能します。ブロックテーマを使用している場合は、方法2に進んでください。

ナビゲーション・メニュー項目をスタイリングする最も簡単な方法は、テーマにフィルターを追加することです。

WordPressのチュートリアルには、テーマのfunctions.phpファイルに追加するコードスニペットがよく掲載されています。

最大の問題は、カスタムコードスニペットに小さなミスがあっただけでも、WordPressサイトが壊れてアクセスできなくなることだ。言うまでもなく、WordPressテーマを更新すれば、カスタマイザーはすべて失われてしまう。

そこでWPCodeの 出番だ。

この無料プラグインを使えば、サイトを危険にさらすことなく、WordPressにカスタムCSS、PHP、HTMLなどを簡単に追加できる。

最初に行う必要があるのは、無料のWPCodeプラグインをインストールして有効化することです。詳しくは、WordPressプラグインのインストール方法のステップバイステップガイドをご覧ください。

有効化したら、Code Snippets ” Add Snippetにアクセスしてください。

Adding a custom code snippet using WPCode

ここで、「カスタムコードを追加」にマウスオーバーするだけです。

表示されたら、『スニペットを使用する』をクリックする。

Adding a custom code snippet to a WordPress website using WPCode

はじめに、カスタムコードスニペットのタイトルを入力します。これは、WordPressダッシュボードでスニペットを識別するのに役立つものであれば何でも構いません。

その後、「コードタイプ」のドロップダウンを開き、「PHPスニペット」を選択する。

Adding a custom PHP snippet to WordPress using WPCode

そして、次のPHPをコードボックスに追加する:

function wpb_first_and_last_menu_class($items) {
    $items[1]->classes[] = 'first';
    $items[count($items)]->classes[] = 'last';
    return $items;
}
add_filter('wp_nav_menu_objects', 'wpb_first_and_last_menu_class');

その後、画面を一番上までスクロールし、「Inactive」トグルをクリックして「Active」に変更すれば準備完了です。

最後に「Save Snippet」をクリックして、PHPスニペットをライブにする。

Adding custom styling to a navigation menu using WPCode

これにより、最初と最後のメニュー項目に .first と .last CSS クラスが作成されます。これらのクラスを使って、これらの項目に独自のスタイルを適用することができます。

そのためには、WordPressサイトに2つ目のスニペットを追加する必要があります。まず、上記と同じ手順でカスタマイザーを新規作成します。

その後、カスタム・コード・スニペットのタイトルを入力する。

次に、「コードタイプ」のドロップダウンを開くが、今回は「CSSスニペット」を選択する。

Styling the first and last menu items using WPCode

このガイドでは、以下のCSSフォーマットをコードボックスに追加することで、最初と最後のメニュー項目を太字にするだけです:

.first a {font-weight: bold;}

.last a {font-weight: bold;}

それが終わったら、「Inactive」トグルをクリックして「Active」に変更する。

Adding custom styling to a menu using code

最後に「Save Snippet」をクリックして、CSSスニペットをライブにする。

今、あなたのサイトにアクセスすると、更新されたメニューがライブで表示されます。

An example of a WordPress menu, created using WPCode

方法2: CSSセレクタを使用して最初と最後の項目をスタイリングする (すべてのテーマで動作)

プラグインを使いたくない場合は、CSSセレクタを使って最初と最後のメニュー項目をスタイルすることができます。ただし、この方法はInternet Explorerのような古いブラウザーでは動作しない場合があります。

このことを念頭に置いて、WordPressサイトをさまざまなブラウザーでテストすることをお勧めします。

この方法に従うには、テーマのスタイルシートまたはWordPressテーマ・カスタマイザーの「追加CSS」セクションにコードを追加する必要があります。

まだカスタムCSSを使用したことがない場合は、WordPressサイトに簡単にカスタムCSSを追加する方法をご覧ください。

最初のステップは、テーマのstyle.cssファイルを編集するか、外観 ” カスタマイザーから「追加CSS」をクリックします。

The WordPress Theme Customizer

その後、以下のコード・スニペットをサイトに追加してください:

ul#yourmenuid > li:first-child { }
ul#yourmenuid > li:last-child { }

yourmenuid’をナビゲーションメニューのIDに置き換える必要があることに注意してください。

セレクタ’first-child’と’last-child’は、ナビゲーション・メニューの最初と最後の項目である親の最初と最後の子を選択する。

例えば、WordPressブログの最初と最後のナビゲーション・メニュー項目を太字にするために、このコードを使用した:

ul#primary-menu-list > li:first-child a {
    font-weight: bold;
}
ul#primary-menu-list > li:last-child a {
    font-weight: bold;
}
Using CSS Selectors to Style First and Last Menu Items Differently

WordPressのブロックテーマを使用している場合、WordPressの管理画面にはテーマカスタマイザーがありません。テーマカスタマイザーにアクセスするには、ブラウザーでこのURLを入力する必要があります:

https://yourdomainname.com/wp-admin/customize.php

ドメインは必ずあなたのサイトのドメイン名に置き換えてください。

その後、先ほどと同じように「Additional CSS」タブを開き、以下のコードをインサーターで挿入する。メニューIDを追加する必要がないので、コードが少し違って見えることに注意してください。

li:first-child a,
li:last-child a {
    background-color: black;
    border: none;
    color: white !important; /* Ensures the color white is prioritized */
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    border-radius: 12px;
}

コードは自由にカスタマイズしてください。下の例では、最初と最後のリンクをボタンにしています。

こんな感じだ:

Inserting custom CSS in the block theme for first and last navigation link styling

このチュートリアルで、WordPressのナビゲーションメニューに.firstクラスと.lastクラスを追加する方法を学んでいただけたら幸いです。WordPress でランディングページを作成する方法についてのガイド、またはドラッグ&ドロップで作成できるページビルダーのベストリストもご覧ください。

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

情報開示 私たちのコンテンツは読者支援型です。これは、あなたが私たちのリンクの一部をクリックした場合、私たちはコミッションを得ることができることを意味します。 WPBeginnerの資金源 をご覧ください。3$編集プロセスをご覧ください。

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

究極のWordPressツールキット

ツールキットへの無料アクセス - すべてのプロフェッショナルが持つべきWordPress関連製品とリソースのコレクション!

Reader Interactions

20件のコメント返信を残す

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Ahmed Mahdi says

    i’ve changed the code slightly to work with child menus too:

    function wpb_first_and_last_menu_class($items) {

    foreach($items as $k => $v){
    $parent[$v->menu_item_parent][] = $v;
    }

    foreach($parent as $k => $v){
    $v[0]->classes[] = ‘first’;
    $v[count($v)-1]->classes[] = ‘last’;
    }

    return $items;

    }

    add_filter(‘wp_nav_menu_objects’, ‘wpb_first_and_last_menu_class’);

  3. Charles says

    Thanks for this nice code…

    What about child menu first and last item?
    It applied only for parent manu.

    Do you have any idea about child last item?

  4. jordi says

    Anyone have any tip about use add_filter(”); for wp_nav_menu using STARKERS?
    can’t make it works :( JS and CSS are fine to do that, it is just frustrating to don’t be able to fix it from the back…
    thanks to share anyway!!

  5. Olivier says

    Together with some other additions to functions.php that i’ve tried, this code fails to tag a menu item as first or last menu item when they are in a submenu. A fix for this would be great!

  6. Mattia says

    Great! This is particularly interesting because I have to class more than 2 menu items…
    Now I got it!

    Thanks

  7. karen says

    Thanks for this! Forgive me if I missed it – but – is there an example of the menu to see the difference in the nav created by this class? Thank you again!

    • Editorial Staff says

      The site we designed for our client is not live yet. But the main reason was that we wanted to have a border left to the first menu item. All other items had border right element with a specific padding and margin. We used the last class to remove the margin right and the border right because there was no need for it. It was hitting the wrap container. Hope you can visualize it.

      管理者

返信を残す

コメントありがとうございます。すべてのコメントは私たちのコメントポリシーに従ってモデレートされ、あなたのメールアドレスが公開されることはありませんのでご留意ください。名前欄にキーワードを使用しないでください。個人的で有意義な会話をしましょう。