WordPress Tips & Tricks: How to use get_posts & get_pages to create custom navigations

In addition to using the wp_get_archives function to display archives, WordPress provides a multitude of other functions that you can use to suit your navigational needs. Two similar functions that come to mind are get_posts and get_pages. The get_posts function returns all the posts that match your criteria while get_pages returns pages.

To illustrate how these 2 functions work lets do a couple basic examples.

Example 1: Showing a Recent Posts links limited to a category

For this example lets assume we have a movie review website that posts reviews as well as news and updates on upcoming releases. In this site we have decided we want to display the user with an archive containing the 5 most recent movie reviews we published. To accomplish this task we would use the get_posts page with the category__in and number_posts parameters. We can specify in the category__in parameter the Movie Review category and set the number of posts to 5 in number_posts. The code would look similar to:

Example 2: Segregating your pages into a main nav and footer nav

With a website you typically have multiple navigation elements the most common being a main navigation on the left or top of your site and a footer (utility) nav on the bottom of the site. To manage the content that appears in these navs you can use the get_pages function to include/exclude content. Lets assume our site has 3 pages we want to display in the footer but not the main nav then we could exclude them from the main nav by:


And include them in the footer nav by:


           |   
ID).'" target="_self">';
        $link .= $pageInstance->post_title;
        $link .= '';
        echo $link;
    }
 ?>

These are two basic examples of what you can do with the get_pages and get_posts functions. To see a full listing of the options you can pass to them check out the WordPress Codex.

Resources

Comments & Questions

Add Your Comment