Current page

Highlight Your WordPress Page Links

Many themes are designed with a simple html and css navigation bar that displays your home page and a list of your WordPress pages. It might look something like the following:

  • Home
  • About Us
  • Services
  • Products
  • Contact

In the above navigation bar each of the links would be a WordPress page with the exception of Home, which would be a link back to your blog’s home page. You can see how About Us is styled differently to indicate it’s the page your visitor is currently viewing. The code WordPress uses to display the html for the above is:

The code above is taken directly from the WordPress default theme, but it’s very typical of free and premium themes as well. The code in the list-item provides a link to your blog’s home page and the following line of code uses a WordPress template tag to run through all your WordPress pages and wrap them in html list-item and link code.

The html that us ultimately produced will look like the following code block. Note that I’ve replaced the actual URL each link would point to with a # for simplicity.

The key to the above code is the class=”current_page_item” which WordPress automatically adds through the wp_list_pages template tag. When your viewing the About Us page the class will be applied to the list-item containing a link to the About Us page. When you’re viewing the Contact page the class will be applied to the list-item for the Contact link.

Given this class will only appear on the currently viewed page all you need to do highlight the page is give the current_page_item class a look that makes it stand out. How you highlight the current page link is up to you and will depend on the style of your theme, but a simple way to highlight the link is to give it a different background-color and a different color for the text itself.

Highlighting Your Main Blog Page

Everything above works great for highlighting the link in your navigation when you’re viewing a page, but what about when you’re on your blog’s home page? The home page link wasn’t being produced with the wp_list_pages tag and won’t automatically have our class applied. We need to find a way to have the class added when you’re viewing the home page.

Fortunately WordPress makes this easy through the use of conditional tags. Combined with a little bit of php we can apply the class just as above. The conditional tag used to check if the current page is your main blog page is called is_home() and the code you would use to add the current_page_item class can be seen below.

Note: If you’ve set WordPress to use a static front page as your home page you’ll want to use the is_front_page() conditional to test the true home page of your site. is_home() tests to see if the page is your main blog page. See Andrew’s comment below.

The code we’re concerned with is:

All the code above is doing is checking to see if we’re viewing the main page of the blog and if so add the current_page_item class to the list-item. The css in place for the pages will do the rest. Pretty simple.

Highlight Blog Posts And Other Blog Pages

Of course your blog has more pages than just the main page. You have post pages, search pages, and archive pages. Your main navigation likely won’t include all these pages, and the code we’ve been using here doesn’t so we’ll highlight the home page whenever we’re viewing one of these other pages.

All we need to do is add a few more conditional_tags to our Home link

is_single tests to see if we’re on a single post page, and is_search and is_archive test to see if we’re viewing any of the search or archive pages as you’d expect. The double pipe || is php to say or. So the statement is testing if we’re on the main blog page or a single post page or a search page or an archive page and if we’re viewing any of those pages add the current_page_item class. Our css will handle the highlighting as it has above.

Nothing too hard right?

The current page

By “current page”, I mean the page you are on right now. It’s this page to you, or to me if I have the vanity to read this post after writing it. In our navigation schema we like to highlight the current page, indicating to the user where they are. A highlighted current page link is like a YOU ARE HERE indicator in a shopping mall floor map. I’m rarely there, incidentally, because I hate shopping.

The problem with “current page” links is there’s no interoperable (read: accessible) way of communicating them. Unlike links to page fragments, which are identified as “same page link” (or similar) by popular screen readers, the mechanism by which a link points to the current location is not exposed via browsers to assistive technologies. At least, not in my experience.

Class confusion

It’s perfectly simple to add a class — either manually or dynamically — to whichever link corresponds to the current page to add our highlight. Drupal adds an active

class to current page links. It’s a poor name because it shares terminology with the :active state, but it does the job.

<nav role="navigation">   <ul>   <li><a href="/" class="active">Home</a></li>   <li><a href="/about">About</a></li>   <li><a href="/contact">Contact</a></li>   </ul>  </nav>

Unfortunately, this class, as all classes, will remain uninterpreted by screen readers. Screen readers do not read classes. Classes do not climb accessibility trees. In order to provide an aural indication of context, we’ll need to try something else.

Accessible names

The accessible name of an element — its lexical content — is calculated by one of

  • the element’s text node,
  • the value of any associated aria-label or aria-labelledby attributes,
  • the alt attribute if it’s an image etc.,
  • the title attribute. Don’t leave it up to the title attribute. That’s flimsy as hell.

Unavoidably, if we want to do the right thing here and communicate the current page both visually and aurally, using an accessible name is the key. First let’s try adding some text.

The span approach

<nav role="navigation">   <ul>   <li><a href="/" class="active">Home <span class=”visually-hidden”>current page</span></a></li>   <li><a href="/about">About</a></li>   <li><a href="/contact">Contact</a></li>   </ul>  </nav>  

This is pretty good, but necessitates the hacky “hide to visual users but not to screen reader users” approach of clipping the <span> text or hiding it off screen. Because the span communicates nothing visually, we are then forced to tackle the same problem separately for visual users: We have to leave the .current class intact.

The aria-label approach

The aria-label attribute can be added to elements which are lacking a text node. Commonly, <button>s with just unicode icons or background images.

   <nav role="navigation">   <ul>   <li><a href="/" class="active" aria-label="current page">Home</a></li>   <li><a href="/about">About</a></li>   <li><a href="/contact">Contact</a></li>   </ul>   </nav>

I prefer this to the “shove a span in there” approach for one reason above all: You can use the aria-label attribute in a selector. By pairing the accessible name with the style you can remove the class, tidying up the HTML. More important than tidiness, though, is the creation of a mechanism whereby the visual appearance of “current page” and the aural announcement of “current page” are paired. That is, when you move the aria-label

between links, you are doing it for both kinds of user.

[aria-label="current page"] {   /* highlighted styles */  }

Roger Johansson notes an internationalization problem with this method. Should we translate the site to French, we would want to change the “current page” value of the aria-label to “page actuelle” or similar. This would break the above selector. You could change the selector to [aria-label] so it just matches the presence of the attribute — which would only be on our current link — but there’s a bigger problem with aria-label than that.

The problem

Having been testing in VoiceOver, I was fully expecting the “current page” text to be appended (or is it prepended? It doesn’t matter) to the text node — “current page home”, for example. Unfortunately, for our purposes, NVDA, JAWS and ChromeVox all override the text node with the label, leaving just “current page”. Irritatingly cryptic to most users, I would imagine…

  • Home
  • About
  • Contact
  • Current page
  • Blog

The aria-describedby approach

Unlike aria-label, aria-describedby is actually specified to append its value to the target element’s text node. I have set up a test case on CodePen where you will note that both JAWS and NVDA both read “home link current page” when focusing the “home” navigation item. The markup looks like this:

<nav role="navigation">   <ul>   <li><a href="/" aria-describedby="current">home</a></li>   <li><a href="/about">about</a></li>   <li><a href="/contact">contact</a></li>   </ul>   <div id="current">current page</div>  </nav>

Naturally, we hide #current with display: none. This will make it invisible to all users. Now, only one item needs translating and it’s easier because it is text which appears within the document rather than an attribute value. The aria-describedby value need not change as it just forms a relationship with #current. This is the best solution I have come up with.


You may or may not know that WAI-ARIA tab interfaces have an aria-selected attribute which can be used to indicate the “open” tab in such an interface. “Selected tab” (or “tab selected”) is communicated whenever the selected tab is focused.

<a role="tab" aria-selected="true">My tab</a>

Note how I have omitted the class. As in our “current page” example there’s no need for it, because the presence of the aria-selected

attribute can do all the work. The W3C recommend tying state to appearance in this way, in fact:

For supporting browsers, tie CSS attribute selectors to WAI-ARIA properties to reduce script

Like aria-checked and aria-pressed, aria-selected is intended to communicate the selected state of a control amongst other controls. It’s tempting to think aria-selected would be suitable for the use case I am exploring for “current” pages, but there are conceptual differences between that which is “on” or “chosen” and one’s location within a continuum. Accordingly, Léonie Watson has been discussing aria-current as a proposed standard method for indicating one’s current location within a site or step-based process. What do you think?

Remove the link?

One more approach, as suggested to me by Jonathan Schofield, would be to remove the link for the current page altogether.

<nav role="navigation">   <ul>   <li><strong>home</strong></li>   <li><a href="/about">about</a></li>   <li><a href="/contact">contact</a></li>   </ul>  </nav>  

Though perhaps a bit more of a handful styling wise, this makes sense to me. Why link to the place you’ve arrived at already? My only concern is that a <strong>, <span> or other inert element would be unfocusable, not allowing a screen reader user the context we are trying to communicate.

This is design

The next time someone asks me what web design is or categorizes me as a “visual designer”, I’m going to send them to this post. You are welcome to as well. Any other suggestions for “current page” solutions, anyone?


Название статьи говорит само за себя, сегодня я хочу рассказать как сделать в WordPress довольно простую, но все же весьма полезную функцию — выделение активной страницы.

Вы удивитесь, насколько просто и легко можно реализовать это в WordPress, дело в том что здесь для этого уже все предусмотрено, вам фактически нужно только прописать в css-файле стиль активной страницы.

Разберем это на простом примере. Ниже приведен небольшой фрагмент кода, для отображения навигации по страницам в WordPress.

  <div id="menu">   <ul>   <li><a href="<?php echo get_settings('home'); ?>">Home</a></li>   <?php wp_list_pages('title_li=&depth=1'); ?>   </ul>  </div>  

Теперь, если сохранить страницу как html, или посмотреть фаербагом, мы увидим примерно следующее:

  <div id="menu">   <ul>   <li><a href="">Home</a></li>   <li class="page_item"><a href="" title="Page 1">Page 1</a></li>   <li class="page_item"><a href="" title="Page 2">Page 2</a></li>   </ul>  </div>  

Обратите внимание, что класс page_item, присваивается только ссылкам, вызванным функцией wp_list_pages, то есть фактически последующие изменения не коснутся ссылки на главную страницу.

Далее, если мы перейдем по ссылке на другую страницу, код html измениться следующим образом:

  <div id="menu">   <ul>   <li><a href="">Home</a></li>   <li class="page_item"><a href="" title="Page 1">Page 1</a></li>   <li class="page_item"><a href="" title="Page 2">Page 2</a></li>   </ul>  </div>  

То есть, к текущей активной странице добавляется класс «current_page_item».  А дальше как говорится дело техники, достаточно назначить соответствующий стиль этому классу в css-файле:

  #menu ul li.current_page_item {  background: #4A7EB8;  }  

В результате, мы получили выделение любой текущей активной страницы (кроме главной) светло-синим цветом (как на картинке в примере).

Если же вам нужно, чтобы главная страница также отмечалась в качестве активной, для этого нужно написать немного php-кода:

  <div id="menu">   <ul>   <li class="<?php if (is_home()) { echo "current_page_item"; } ?>">   <a href="<?php echo get_settings('home'); ?>">Home</a>   </li>   <?php wp_list_pages('title_li=&depth=1'); ?>   </ul>  </div>  

В вышеприведенном коде, задействован условный тег Woprdpress is_home(), который проверяет является ли текущая страница домашней, то есть главной, и если это условие выполняется, то к ней также добавляется класс current_page_item.

С помощью условных тегов WordPress, можно делать и другие интересные вещи, но об этом мы поговорим в следующей статье.

Вольный перевод статьи: WordPress: Active Page Tabs

Copyright © 2010-2018, Англо-русский словарь Онлайн. Бесплатные русско-английские словари и энциклопедия, транскрипция и переводы английских слов и текста на русский.
Free online English dictionaries and words translations with transcription, electronic English-Russian vocabularies, encyclopedia, Russian-English handbooks and translation, thesaurus.

You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.