Creating Navigation

In this chapter, we will cover:

► Listing all of the pages that exist on a blog

► Listing all of the categories defined for a blog

► Listing all of the tags in use on a blog

► Highlighting the current page in the navigation

► Adding a search function to a theme

► Getting the category page link from a category name

► Displaying page links only if the destination page exists

► Creating a category drop-down menu

► Creating drop-downs using child pages

Introduction

One of the most important aspects of any website is navigation. Making sure that a visitor can get around is paramount to increasing traffic, user engagement, and visit length. By offering a variety of navigation methods, you give the user multiple ways to find the content that interests them. There are several techniques built into WordPress that you can use to build the navigation that lets your users find what they need on your site.

When thinking about the topic of navigation in the context of this chapter, it is important to also consider the subject as a whole. Don't limit yourself to the concept of a top or side main navigation item. Those types of navigation are very important, but for the purposes of this chapter, you'll consider navigation as a whole—meaning any way that helps the user to get around your site.

Listing all of the pages that exist on a blog

WordPress pages often contain static content that should be reachable at any time. Common uses for WordPress pages are website and author descriptions, contact forms, affiliate information, and more. Making sure that these pages can be found and navigated to quickly is paramount.

First, decide where you want to generate a linked list of all your pages. If you're comfortable using pages for navigation, then you probably want to put the pages listing directly below your main site identification elements, in header.php. Open your chosen template file and insert the following:

Next, open your theme in your browser and take a look at the spot where you inserted the appropriate code. Depending on your site's styles and the pages that you've created, the output for this function call should look like the main content area in the following screenshot:

Remove Title Page Pagenav List Pages

When you call wp_list_pages, WordPress performs a database query, fetching the appropriate pages based on the parameters that you pass to the function. After fetching the pages, WordPress builds the markup for the list. The markup consists of an <li> tag containing a link to the page for each page that was fetched. If the title_li parameter is not empty, then the entire list is wrapped in a containing <li>. By default, the previous code will produce markup that is similar to the following:

<li class="pagenav">Pages<ul>

<li class="page_item page-item-271"> <a title="Affiliates"

href="http://themes.local/affiliates/">Affiliates</a> </li>

<li class="page_item page-item-269"> <a title="Authors"

href="http://themes.local/authors/">Authors</a> </li>

<li class="page_item page-item-267"> <a title="Contact"

href="http://themes.local/contact/">Contact</a> </li>

<li class="page_item page-item-2 73"> <a title="Terms &amp; Conditions"

href="http://themes.local/terms-conditions/">Terms &amp; Conditions</a> </li>

<li class="page_item page-item-256 current_page_item"> <a title="WP List Pages"

href="http://themes.local/list-pages/">WP List Pages</a> </li> </ul> </li>

The default output for wp_list_pages might not fit your specific use cases. Luckily, modifying the output from wp_list_pages is easy.

Passing parameters

The wp_list_pages output can be changed by passing different values for a wide array of parameters, as follows:

<?php wp_list_pages(array('parameter_name' => 'parameter_value')); ?>

Some of the more important parameters are as follows:

Parameter Name Effect echo Set to false to cause wp_list_pages to return a string containing

HTML markup instead of printing the markup child_of Pass a numeric ID to only retrieve child pages of the page with that ID

exclude Pass a comma-delimited list of page IDs (for example: '#,#,#') to exclude them from the pages displayed

Taking this into account, consider the case where you only want to display pages that are a child of the affiliate information page. If the affiliate information page has an ID of 4, then you would use wp_list_pages as follows:

<?php wp_list_pages(array('child_of'=>4)); ?>

For more information on the available parameters, visit http://codex.wordpress.org/ Template_Tags/wp_list_pages.

Listing all of the categories defined for a blog

Proper categorization of posts is a great way to help visitors find what they are looking for. To make it even easier, a theme could include a list of all of the categories in which there are posts. This technique works best on blogs with a small number of categories.

Alternatively, you can use category drill-downs that change based on the category level that you're at. If you're writing a site about music, you might have Rock, Hip Hop, and Country as toplevel categories, each containing second-level categories such as Reviews, Recommendations, and News. In this way, your users can navigate directly to the information that they're looking for, quickly and easily.

First, decide where you want to generate a linked list of all of your categories. If you're taking a drill-down approach as talked about in the introduction to this recipe, then you may wish to put the list of links in the header of your site. Otherwise, category links would be best served in a sidebar or footer. Open the appropriate template file and insert the following:

Next, open your theme in your browser and take a look at the spot where you inserted the appropriate code. Depending on your site's styles, and the categories that you've created, the output for this function call should look like the following:

Menu Php List Categories

When you call wp_list_categories, WordPress performs a database query, fetching all of the categories that match the parameters that you pass to the function. After fetching the categories, WordPress builds the markup for the list. The markup consists of an <li> tag containing a link to the categories archive page for each category that was fetched. If the title_li parameter is not empty, then the entire list is wrapped in a containing <li>. By default, the previous code will produce markup that is similar to the following:

<li class="categories">Categories<ul> <li class="cat-item cat-item-3">

<a title="View all posts filed under aciform" href="http://themes.local/category/aciform/">aciform</a> <ul class="children">

<li class="cat-item cat-item-41">

<a title="View all posts filed under sub" href="http://themes.local/category/aciform/sub/">sub</a> <ul class="children">

<li class="cat-item cat-item-102">

<a title="View all posts filed under sub sub" href="http://themes.local/category/aciform/sub/sub-sub/" >sub sub</a> </li> </ul> </li> </ul> </li>

<li class="cat-item cat-item-4">

<a title="View all posts filed under antiquarianism" href="http://themes.local/category/antiquarianism/" >antiquarianism</a> </li>

<li class="cat-item cat-item-5">

<a title="View all posts filed under arrangement"

href="http://themes.local/category/arrangement/">arrangement</a> </li>

<li class="cat-item cat-item-6">

<a title="View all posts filed under asmodeus" href="http://themes.local/category/asmodeus/">asmodeus</a> </li>

<li class="cat-item cat-item-7">

<a title="View all posts filed under broder" href="http://themes.local/category/broder/">broder</a> </li>

<li class="cat-item cat-item-8">

<a title="View all posts filed under buying" href="http://themes.local/category/buying/">buying</a> </li> </ul> </li>

The default output for wp_list_categories might not fit your specific use cases. Luckily, modifying the output is easy.

Passing parameters

Similar to wp_list_pages, the categories retrieved by wp_list_categories can be modified by passing parameters to the function. Parameters are passed as follows:

<?php wp_list_categories(array('parameter_name' => 'parameter_value')); ?>

Some of the more important ones are as follows:

Parameter Name

Feed current category

Pass a numeric value to limit the number of categories retrieved. This is especially helpful for blogs with a large number of categories.

Pass true to cause a link to each category's feed to be printed

Pass the ID of a category to force the output to contain the current-cat class on a particular category.

For example, say you wanted to limit your category list to the first five categories. To do so, you would use the following code:

<?php wp_list_categories(array('number' => 5)); ?>

For more information on the available parameters, visit http://codex.wordpress.org/Template_Tags/wp_list_categories.

Listing all of the tags in use on a blog

Generally, tags are used liberally to indicate the subject matter of a post. For this reason, a list of tags is a great way to help visitors to get around a blog and view a wide array of posts that they're interested in. By default, WordPress lists tags in a cloud, varying the size of each tag according to the number of times it was used. However, this default output can be modified to produce a list that might make more sense to your users.

First, decide where you want to generate a linked list of all of your tags. Open the appropriate template file, and insert the following:

<?php wp_tag_cloud(array(

Next, open your theme in your browser and take a look at the spot where you inserted the appropriate code. Depending on your site's styles, the output for this function call should look like the example shown in following screenshot:

□ WP List Tags

O It il http://themes.lDcal/list-pages/

Theme Testing Platform

Skip Navigation

Just another Themes.hca! weblog

=

Contact Authors Affiliates Terms & Conditions WP List Tags

• chattels

• cienaga

Search

• clavcold

To search, type and hit enter

• crushing

• dinarchy

• doolie

RSS Links

• energumen

* All posts

• ephialtes

* All comments

• eudiometer

• figuriste

Meta

* habergeon

* Site Admin

• hapless

• Log out

• hartshorn

• hostility impregnability

• impropriation

• knave

• misinformed

When you call wp_tag_cloud, WordPress performs a database query, fetching all of the tags that match the parameters you pass to the function. After fetching the tags, WordPress builds the markup for the list. Using the parameters in the previous code, the markup consists of an <li> tag containing a link to the categories archive page for each category that was fetched. The entire list is then wrapped in a containing <ul> tag, producing output similar to the following:

<ul class="wp-tag-cloud"> <li>

<a style="" title="1 topic" class="tag-link-53" href="http://themes.local/tag/chattels/">chattels</a> </li> <li>

<a style="" title="1 topic" class="tag-link-54" -[36]-

href="http://themes.local/tag/cienaga/">cienaga</a> </li> <li>

<a style="" title="1 topic" class="tag-link-55" href="http://themes.local/tag/claycold/">claycold</a> </li> <li>

<a style="" title="1 topic" class="tag-link-56" href="http://themes.local/tag/crushing/">crushing</a> </li> <li>

<a style="" title="1 topic" class="tag-link-58" href="http://themes.local/tag/dinarchy/">dinarchy</a> </li> <li>

<a style="" title="1 topic" class="tag-link-59" href="http://themes.local/tag/doolie/">doolie</a> </li> </ul>

You'll notice that each of the <a> tags that link to the tag archive page has an empty in-line style attribute. This is a consequence of the processing that wp_tag_cloud does internally. You'll also notice that unlike wp_list_pages and wp_list_categories, this function produces a surrounding <ul> element for its items.

In most cases, the default display of wp_tag_cloud will not be the one that is most beneficial to your users. This is especially true for business blogs and professional sites. Luckily, there is an easy way to change how wp_tag_cloud displays.

Passing parameters

As seen earlier, the output from wp_tag_cloud can be modified by using parameters with the function call. Parameters are passed in the same way as with many other WordPress functions, which is in the following format:

<?php wp_tag_cloud(array('parameter_name' => 'parameter_value')); ?>

You've already seen a couple of the parameters that wp_tag_cloud supports. Another important one is the number parameter, which limits the number of tags placed in the cloud. If you wanted to limit the number of tags to 5, then you'd call the function as follows:

<?php wp_tag_cloud(array('number' => 5)); ?>

For more information on the available parameters, visit http://codex.wordpress.org/Template_Tags/wp_tag_cloud.

Highlighting the current page in the navigation

One easy way to provide a great user experience is to make sure that the user's current location on a website is plainly visible to them. The best way to accomplish this is to visibly highlight the navigation item for the page that the user is on.

First, ensure that you have used wp_list_pages to generate a list of links for use in navigation. Most likely, you'll do this in the site header where your main navigation is located. After you've done this, open your theme's stylesheet (style. css) and add the following CSS:

.current_page_item a { color: #fff; background: #00 0;

If you've done everything correctly, depending on your theme's styles, you'll see something like the following on your home page:

After you navigate to the page with the title Lorem Ipsum, you'll see the following on your home page:

When wp_list_pages creates output, it adds the current_page_item class to the list item for the page that is currently being viewed. You style this class to ensure that the current page appears differently from other pages.

The previous CSS code simply changes the background color of the list item to black, while changing the text color to white. However, you can use any CSS declarations to customize the style of the highlighted item to your heart's content.

If your blog has a small number of top-level categories and you are using wp_list_ categories for your main navigation items, you might want to take advantage of the highlighting capabilities demonstrated for pages. Doing so is easy, because you can use the earlier-featured code in full. You just have to change the targeted class from current_page_item to current-cat, as follows:

Adding a search function to a theme

In spite of your best efforts, static navigation for a website will always be left wanting when a user wants to quickly and easily find content matching a specific term or phrase. That is where search comes in, and with WordPress, it is easy to implement.

Open your theme and decide where you want to place the search form. The best place for a search form is either in the header or at the top of a sidebar in the site. When you figure out where you want to place the search form, insert the following code at the appropriate place:

<form method="get" id="searchform" action="<?php echo site_url('/'); ?>">

<label class="hidden" for="s"><?php _e('Search for:'); ?></label> <div>

<input type="text"

value="<?php echo attribute_escape(get_search_query()); ?>" name="s" id="s" />

<input type="submit" id="searchsubmit" value="<?php _e('Search'); ?>" /> </div> </form>

After you've inserted the search form markup, style the form elements as desired. By default, you'll end up with output that looks like the following:

Search for:

Search

In this recipe, you've created the standard markup for a WordPress search form. In the markup, there is a label describing the search input, the search text input itself, and the submit button for the form. When a user types text into the form and submits it, WordPress detects the parameters contained in the query and responds accordingly.

Of particular note in this recipe is the use of two WordPress functions. The first is get_search_ query. This function retrieves the search query text that a user submitted, so that the user can see what they searched for. In addition, the site_url function is used to output the home page for the blog. This function is a handy utility that lets you easily construct URLs to your site.

Searching is a complicated thing, and many developers feel that the default search functionality in WordPress is inadequate. Luckily, because of WordPress' extensive plugin system, there is a solution. That solution is the Search Everything plugin by Dan Cameron of Sprout Venture.

The Search Everything plugin, found at http://wordpress.org/extend/plugins/ search-everything/, allows for searching tags, categories, pages, comments, and more. It might be a great addition to your WordPress installation, so check it out.

Getting the category page link from a category name

There are several situations where a particular category should be linked to directly. If the name of the category is known, but the ID of the category could differ (for instance, between production and development environments), then it is useful to be able to retrieve the category page link directly from the category name. In addition, it is helpful to not display the link at all if the category doesn't exist.

For this recipe, consider the situation where you need to link to three different categories: Testimonials, Portfolio, and Thoughts. You've established each of these categories in your local development environment and in your staging environment, but you haven't yet created them on the blog where you'll be launching your theme. This is a good situation to use conditional linking.

Given this situation, you need code similar to the following:

$nav_categories = array('Testimonials,/,Portfolio,/,Thoughts'); ?>

<ul id="site-nav"> <?php foreach($nav_categories as $cat_name) { $cat_id = get_cat_ID($cat_name);

<a href="<?php echo get_category_link($cat_id); ?>"> <?php echo $cat_name; ?> </a> </li>

This code produces a nice list of links for the categories that exist. You remove the chance of fatal errors from using non-existent categories, and you provide your users with a better experience.

The get_cat_iD function returns the ID for a specific category name. If a category with that name does not exist, the function returns the value 0. Therefore, the condition that checks the $cat_id variable will prevent the system from trying to retrieve a link for categories that do not exist. If the category does exist, the category link will be displayed appropriately.

Displaying page links only if the destination page exists

In themes intended for distribution, you may want to provide a link to an About or Contact page somewhere in the theme template. However, you won't want to display the link if the page doesn't actually exist. To get around this, you can use some WordPress functions to see if the destination page exists.

Identify all of the pages that you wish to link to individually in your theme. For each of them, insert the following code, replacing Page Name with the name of the page you're referencing:

$page = get_page_by_title('Page Name'); if( null !== $page ) {

echo '<a href="' . get_page_link($page->ID) . '">Page Name</a>';

The get_page_by_title function returns an object containing all of the information about the page with the specified title if the page exists. If the page does not exist, the function returns null. In this recipe, you check the value of the $page variable to make sure that the page exists. If it does, a link to the page is printed, utilizing get_page_link to retrieve the correct URL for the page.

get_page_link respects the front page options of WordPress and bypasses a lot of checks that get_permalink has for non-page links. If you know that you are linking to a page and not a post, you should use get_page_link.

Creating a category drop-down menu

For highly-categorized and deeply-hierarchical sites, showing a full list of categories and subcategories can take up a lot of space in your design. To get around this, you can change your categories list from static to dynamic by using a simple JavaScript technique.

First, download the Superfish package from http://users.tpg.com.au/j_birch/ plugins/superfish/ and place all of the JavaScript files contained within it in your theme directory. Next, insert the following code in your theme's <head> section, above the wp_head function call:

<?php wp_enqueue_script('superfish', get_bloginfo( 'stylesheet_directory' ) . '/superfish.js', array('jquery'));

Place the following code after the wp_head call:

<script type="text/javascript"> // <![CDATA[

jQuery(document).ready(function() { jQuery('ul.superfish'). superfish(); }); // ]]> </script>

Now, open the template file in which you wish to display your Category drop-down. Insert the following:

<ul class="nav superfish">

<?php wp_list_categories(array(,title_li,=>,,,,hide_empty,=>false));

Finally, load your page. Unstyled, you'll see something like the following:

* personable

* propylaeuin

* pustule

* quartern

* scholarship

* selfconvicted

When you hover over a category name that has a child, you'll see the following:

Parent »

■ Child 1 »

* Child 2

*

personable

*

propylaeum

pustule

quartern

*

scholarship

#

selfconvicted

The Superfish script is a JavaScript solution to realize true cross-browser drop-downs. It takes advantage of the semantic markup generated by the wp_list_categories function to create drop-downs with fully-realized submenus for subcategories. The internals of Superfish are beyond the scope of this recipe.

The empty title_li parameter in this recipe prevents a separate list item containing a title string from being generated and displayed. This extra list item could prove confusing to users and should generally be removed with this parameter, when using categories for navigation.

Creating drop-downs using child pages

Complex sites can be created with WordPress by using only the system of pages and subpages. In order to allow the user to easily drill down through a topic, it can be beneficial to create drop-downs from the parent-child page relationship.

Getting started

For this recipe to be useful, you must first create a series of pages and subpages that you'll be using for your site's content. An example of a desirable hierarchical content organization that would be useful to structure in this way would be a top-level "Teams" page with subpages for each team in the league that you're writing about.

Follow the steps for the recipe Creating a category drop-down menu until you get to the point where you use the function wp_list_categories. Then insert the following code:

<ul class="nav superfish">

<?php wp_list_pages(array(,title_li,=>,,)),• ?> </ul>

Depending on your theme's styles, you should see something similar to the following, before hovering over a parent page:

* About

* Lorem Ipsum

And you should see the following after hovering over a parent page:

Again, the semantic markup output by the wp_list_pages function is the real star here. The Superfish JavaScript takes the nested lists generated by WordPress and transforms them into easy-to-use and efficient drop-down menus. The internals of the Superfish JavaScript is beyond the scope of this recipe, but the basic idea is that it uses hover events on the hierarchical list items to make the drop-downs work appropriately.

See also

► Creating a category drop-down menu

0 0

Post a comment