Archive for category templates

Advanced Power Tips For WordPress Template Developers

Smashing-magazine-advertisement in Advanced Power Tips For WordPress Template Developers
 in Advanced Power Tips For WordPress Template Developers  in Advanced Power Tips For WordPress Template Developers  in Advanced Power Tips For WordPress Template Developers

Spacer in Advanced Power Tips For WordPress Template Developers
Back in July, “Power Tips for WordPress Template Developers” presented 8 basic techniques for adding popular features to the front end of a WordPress-powered website. The premise was that WordPress has become an elegant, lightweight content management solution that offers the fundamentals out of the box, atop a modular core that offers incredible potential in the hands of a capable developer.

WordPress does not try to be an “everything to everyone” CMS right out of the box. Many systems do an average job incorporating 99% of what the potential CMS market might need, even if the last 15-20% is used only by a fraction of the market and adds considerably to the system’s overall “heft” (or bloat). At the other end of the spectrum are completely custom solutions that are finely tailored to exact needs, at the cost of reinventing wheels like polished content editing with media management and version control.

The self-proclaimed WordPress “code poets” have, alternatively, focused on doing an A+ job with the “fat middle”: the 80-85% of features that almost everyone needs, and coupling those with a first rate framework and API that enables capable developers to add in almost any niche or “long tail” feature. In fact, the core WordPress framework is so capable that a handful of “intermediary” frameworks that sit on top of it have already emerged.

That previous “Power Tips” entry scratched the surface, covering a handful of API calls mixed in with some simple PHP code and configuration tips intended to help beginner WordPress template developers kick their game up a notch. This article takes power tips to the next level, expanding on some of the topics in the first article, and introducing more advanced techniques and methods for customizing not only the front end, but the content management (or back end) experience.

You may be interested in the following related posts:

Multiple Column Content Techniques

The average blog or website has a single, clearly defined block of space for a given page’s or post’s unique content. But there are plenty of creative websites that don’t conform to this simple notion of “one unique block” per page. A creative online portfolio layout might feature a screenshot and project description in a left column, and a list of technologies used in a right column. Both the left and right column are unique to each portfolio page.

Here’s a screenshot from an in-development website project, built on WordPress. The “projects” area features portfolio-like layouts of green building projects throughout the state. In addition to a specially designed gallery visualization, note that the individual project profile has two distinct columns.

Rigbc-2-column in Advanced Power Tips For WordPress Template Developers

A more commonplace layout might feature an obvious, primary block of page content, but also feature a sidebar element that is unique to the current page: maybe a quote from a customer about a specific product or service. The “Power Tips” article offered a method to associate sidebar elements with multiple pages using custom fields and page IDs (tip #6). That approach isn’t very effective or efficient for designs with a 1:1 relationship between sidebars and pages (where each page has a unique sidebar element).

Sidebars in Advanced Power Tips For WordPress Template Developers

Yes, the developer could add table buttons to the WordPress editor, and let content authors fend for themselves: a solution prone to problematic layouts and bad output relied upon far too often. Here are a few simple options that keep layout in the hands of the template developer while making content management easier and problem-free.

Short, simple, and HTML free? No worries.

Before we delve into solutions that assume a need for HTML formatting in this second content block, let’s review a more basic solution. If the second column does not need to be formatted – or maybe should not be formatted by the editor for design reasons – then a simple custom field will do the trick. In the case of a simple sidebar element, like a customer quote, this may be just the trick.

There are already great tutorials and useful custom fields hacks that walk through the WordPress custom fields feature, so if you are not familiar with the basic idea behind custom fields, start there. Let’s go ahead and create a custom field named “sidebar_content” (also known as the “key”), and put some simple content in there. Just to shake things up, let’s assume we do need a very basic HTML feature for our content authors, who know nothing about HTML: line and paragraph breaks. Let’s also assume that we want to format this sidebar content on the front end with some of the basic automatic niceties we get when we output post content, like curly quotation marks.

Sidebar-custom-field in Advanced Power Tips For WordPress Template Developers

Here’s how we can output this in any template file, using the “the_content” filter to apply the WordPress content filter to our custom field. That filter converts single line breaks to break tags, double line breaks to paragraphing tags, and even transforms simple quotation marks to curly quotes!

$sidebar_content = get_post_meta($post->ID, "sidebar_content", true);

if ($sidebar_content) {
   echo '<div id="sidebar_content">';
   echo apply_filters("the_content", $sidebar_content);
   echo '</div>';
}

Of course, we can make this even more intuitive for the content authors by creating a new meta field box for sidebar content instead of relying on the generic “custom fields” box… which will be covered later in this article!

Using the More Tag for… More

The WordPress editor has a button “more tag” button that is primarily intended to separate “above the fold” content from “below the fold” content. If you are not already familiar with the “more” divider, read up on that first.

If the pages or posts that need a two column layouts also rely on traditional more separation, this tip will most likely not be effective, unless one of the columns is also the intended “above the fold” content. However, most instances where a two column layout is desirable don’t overlap with a traditional above / below the fold need. It is fairly rare, for instance, for pages (vs. posts) to actually make any use of the more tag. So let’s start taking advantage of that feature!

The basic idea is that content above the more divider will represent one block of HTML content, while content below the divider will represent a second block (be it a sidebar element or column).

Sidebar-using-more-tag in Advanced Power Tips For WordPress Template Developers

Here is how to retrieve content above and below the more divider as separate blocks of HTML content in the corresponding page template file.

global $more;

$more = 0;
echo '<div id="column_one">';
the_content('');
echo '</div>':

$more = 1;
echo '<div id="column_two">';
the_content('',true);
echo '</div>';

The global “more” variable lets WordPress know whether or not the content is being rendered in an “above the fold” (or “teaser”) only view. By passing an empty string to “the_content”, we prevent a “read more” link from showing up below the HTML content. And, for column two, we pass a second parameter to “the_content” – true – which instructs WordPress to output the content without the teaser.

If the intent is to output the second block of content outside of the loop in another template element, such as a sidebar, this approach is a bit trickier. One option would be to store the second block of content in a uniquely named variable, declare it as a global variable in the sidebar, and – if there is any content inside the variable – output a new block. An alternative could involve checking which page template is in use with the “is_page_template” function, and, if the two column template is in use, calling “the_content” with the second parameter set to true, as in the example above.

The Plug-in Solution: Adding a Second HTML Content Block to the Editor

The ideal solution, of course, might be a second HTML editor field on the WordPress page or post editor. Unfortunately, no such plug-in existed… until recently! While writing this article, we decided it was time such a solution did exist, and so the author of this article is happy to present a free, open source plug-in that combines some savvy understanding of how TinyMCE works (hint: it’s as simple as a class name) with the custom meta box tutorial covered later in this article, and a little bit of extra customization and polish thrown into the mix.

Secondary HTML Content adds a second HTML editor to pages, posts, or both (customizable with a simple settings panel). You can output the content in a sidebar with an included widget, or integrate it more tightly with the template by using “the_content_2″ and “get_the_content_2″ functions.

Secondary-html in Advanced Power Tips For WordPress Template Developers

Associating Pages with Post Content: Reloaded

“Power Tips” covered the basic foundation for associating different WordPress pages with different post categories. The basic premise was that many sites require, effectively, different post “feeds” on different pages. For instance, there may be a company blog, but there may also be an independent news feed.

This continuation offers specific tips that extend the core concept introduced in part 1, making it easier to have multiple page / category associations, preventing entrance into the “real” category archive, and ensuring that individual post views retain a visual and architectural association with their parent “category page” layout.

Be sure to read part 1 before proceeding.

A Review of the Basics & the Two Fundamental Approaches

At the heart of the category / page association (covered in part one) was:

  • A matching of the “page slug” with the “category slug.”
  • Using “query_posts” and the category parameter to exclude standalone page categories from the primary feed
  • Using a dedicated page template with “query_posts” and the “category name” parameter to create a page featuring a feed for a single category.

Wp-cat-config in Advanced Power Tips For WordPress Template Developers

Before delving into the tips that extend those ideas, it is important to make a distinction between two common but fundamentally different use cases for page / category association. The more typical use case, which the first part was tailored to, is a website that has a primary feed, like a blog, but also has one or two distinct feeds, most often for a formal news or press feed.

The second use case is a bit more esoteric: there is no primary feed. The site has many pages, and many (but not all) of those top level pages are individual feeds of posts. The example, at the end of this power tip, m62.net, is one such use case. Another common use case might be – again – a portfolio centric website.

Let’s say we want to create “Joe’s Portfolio”, and Joe wants to feature 4 distinct areas of expertise. Each area of expertise should be a top level page, say, joes-portfolio.com/web-design, joes-portfolio.com/graphic-design, etc. Joe wants to have a little write-up about each service area at the top of the page, followed by a feed of case studies. Why a feed instead of sub-pages? Maybe Joe wants prospects to be able to subscribe to an RSS feed for each area of expertise; maybe he wants to easily cross-tag case studies based on industry; maybe he plans to update frequently and doesn’t want a huge page sitemap or wants visitors to page through a date-organized collection of case studies. There are many reasons to use posts instead of pages.

The following tips provide solutions for both use cases.

Automatically Determining the Page / Category Association

Part one suggested that a unique page template be created for any page associated with a category. That page template would then query for posts using a hardcoded category name or category ID. If there are only one or two standalone “category pages”, this is an efficient and effective solution.

However, if there are many page / category associations, as in use case #2 (no primary feed), the process of manually creating page templates for each association is tedious to build and maintain, and not realistic if content editors who don’t program need to be able to create more page / category associations on demand.

An alternative would be to create a generic page template, let’s say “template-category-connector.php”, that is assigned to all pages associated with a category, and automatically determines the right category to query.

The following code performs the matching and executes the post query. The magic happens by taking advantage of our matching page and category slugs. Once again, if the website does not use permalinks, an alternative approach will be required (one permalink-free alternative could involve a custom field with the associated category ID).

$cat = get_category_by_slug($post->post_name);
query_posts('cat='.$cat->term_id);

That’s all there is to it… just proceed on with the post loop to output the applicable category’s posts. Note that the template should probably check for an actual return value from line 1, and output a graceful error in the event there is no match.

Handling Entry into the “Real” Category Archive

Now that there is a dedicated page layout that handles the category feed, we will want to be make certain that the visitor doesn’t land on WordPress’ default category “archive” view. For instance, when using permalinks with the default “category base” value, the archive view for a category with a top level category assigned a “web-design” slug would be: mysiteurl.com/category/web-design. However, the intent is for visitors to view this category at our top level page: mysiteurl.com/web-design.

By combining the WordPress category template file with some smart redirects, we can prevent entry into the default category archive. Out of the box, the WordPress template system allows developers to create global category archive templates as well as templates for individual category archives.

If we are in use case #1 – a site with a traditional blog feed and a standalone news feed on a “press releases” page – we will want to use the latter solution. Let’s say, as in part one, the category ID for “press releases” is 5. We create a template file in our theme folder named category-5.php. Under use case #2 (no primary feed), we will want to redirect all category archive traffic, in which case we need to work with the category.php template file.

A few lines of code in either template file will redirect visitors to the right place. We’ll also pass HTTP error / redirect code “301″ – which will tell search engines to permanently redirect their link to the right location. Note that this particular code assumes we are using a permalink configuration. Line 2 can be modified to accomodate that situation.

$destination = get_bloginfo('url');
$destination .= str_replace('/'.get_option('category_base').'/','/',$_SERVER['REQUEST_URI']);
wp_redirect($destination, 301);

In effect, that code removes the category base (”/category” by default) from the overall relative URL, and safely redirects the visitor to the page with the matching slug. Of course, if the site falls under use case #1 (one or two stand alone feeds), the line three could dropped into a specific category template (i.e. category-5.php) with a hardcoded absolute URL for the redirect destitation.

Hiding Standalone Categories from the Category List & Primary Site Feed

In the first use case (only isolating one or two categories from a primary feed), it may be necessary to prevent isolated categories or the posts within those categories from appearing in some common theme elements that would traditionally include them.

Consider the example from part one: a site with a traditional blog and a standalone press release feed. Assume the owners of the site want the RSS feed for the blog to be persistently available throughout the site (typically manifesting itself as an RSS icon in the browser location bar), but don’t want the press release items included in that primary feed. By default, the WordPress primary feed is available at “/feed”, and includes all published posts, regardless of category or any other post property.

Smashingmag-feed in Advanced Power Tips For WordPress Template Developers

To exclude categories from the primary RSS feed, we need to filter the WordPress function that retrieves the posts. Let’s again assume that the category ID for Press Releases is 5. The following code should be placed in the template’s “functions.php” file.

add_filter('pre_get_posts','exclude_press');

function exclude_press($query) {
   if($query->is_feed && !$query->is_category) $query->set('cat','-5');
}

To summarize, we use the “pre_get_posts” filter to modify the post query before it executes. Within a new filter – named “exclude_press” – a conditional confirms that the post query is for a feed, and that the query is not for an individual category. If the check pans out, the query is modified to exclude category 5 before execution.

The notion of globally filtering the post query may have broader implications depending on the site’s unique requirements. With some smart conditional checking, the filter could be extended to prevent the category from appearing anywhere except within the category or isolated post view. But be careful when extending the filter, and be sure to consider all possible views, including administrative views!

The category list is another frequently used site element that isolated categories should, in most cases, be excluded from. If the template calls the category list in only one or two places by code (as opposed to using the categories widget), excluding categories from the list is straight forward.

wp_list_categories('exclude=5');

However, if the categories widget is in use, or the category list is used throughout the template, an alternative approach is required. Enter the “list_terms_exclusions” filter. Again, the following code should be placed in the “functions.php” template file.

add_filter('list_terms_exclusions', 'filter_press');

function filter_press($exclusions) {
   $exclusions .= " AND t.term_id != 5 ";
   return $exclusions;
}

The return value of a “terms exclusions” filter is tacked onto the “where” clause in the SQL query that retrieves the terms. Without digging too deep here, the reason for discussing “terms” as opposed to, say, “categories” is because WordPress abstracts a variety of different taxonomies (link categories, post categories, tags, custom taxonomies, etc) into a unified database model that handles all taxonomies. Calls to “get categories”, “get tags”, and so forth, are all referring back to general “terms” behind the scenes. Ever wonder why category, tag, and other IDs tend to jump around? They are all being added to the same table. Assuming a fairly clean install, try adding a new post category, and note the ID. Then add a tag, and note its ID… one greater than the new post category.

Term-taxonomies in Advanced Power Tips For WordPress Template Developers

Retaining the Page Layout for Post Views within a Category Page

One of the most common challenges to tackle with page / category association is retaining a sense that the visitor is still within the “category page” hierarchy – and not a global feed hierarchy – when a visitor is reading an individual post. Part one hinted at this challenge under “The devil is in the details,” and started to suggest a path that incorporated using the “in_category” function. We will explain how to use “in_category” within templates, as well as how to trick functions that reference the original query object into thinking that they are “within” the category page.

Let’s start with case #1, and building on the example in the first article, assume we only need to contend with one isolated feed, “Press Releases” (category ID 5).

Say the theme has a sidebar template that lists post categories when rendering the blog part of the site, and when rendering a standalone page, shows a page list instead. Here’s an extremely simplified version of what that might look inside the sidebar template file.

if (is_page())
{
   wp_list_pages();
}
else
{
   wp_list_categories();
}

Of course, there may be alternative widget sets for pages or posts, and there is likely to be more than just one element in the sidebar. But the concept should hold. Now going back to the example, the theme should render posts in category 5 (Press Releases) as if the visitor were on a page (not the blog). Leveraging the “in_category” check, the code above would now like the following:

if (is_page() || in_category(5))
{
   wp_list_pages();
}
else
{
   wp_list_categories();
}

Note that if there are multiple categories whose posts should resemble page output, the “in_category” function should be passed an array of IDs, like so:

in_category(array(5,7));

The need for a “in category” check is probably moot in case #2 (multiple page/category associations, without a primary feed): the template is probably structured to output the same elements on pages and posts from the get go. In other words, everything is handled as if it is a page since there is no primary feed. However, the following tip – that dynamically looks up the faux parent page ID (the page associated with the category) – is necessary for the next part of this tip. Just amend the code to check if “faux_parent_page” has a valid value: if it does, then the post is inside an isolated category associated with a page.

Once again, this approach to dynamically seeking the faux parent page (the category page) depends on taking advantage of the matching permalink structure between post categories and pages that is at the heart of this association. If the site is unable to use permalinks, a more complex alternative look up of the faux parent page will be necessary.

foreach(get_the_category() as $category) {
   $faux_parent_path = '/'.get_category_parents($category, FALSE, '/', TRUE);
}
$faux_parent_page = get_page_by_path($faux_parent_path)->ID;

Now that we have the ID of the category’s associated page, we can trick “black box” theme elements that determine page or post properties on their own (by referencing the post query) into thinking they are actually working with the category page.

The most common use case is page navigation. Whether its breadcrumbs, a top level page menu that should retain “current” (on) states, or a side navigation menu that should display the current section, there are many “black box” navigation functions that need to be tricked into rendering themselves as if on the category page.

Let’s use a simple top level page list, which should maintain proper “current_page”, “current_page_parent” (and so on) classes when on a post under a category page. Here’s what that simple function might look like before our changes:

wp_list_pages('depth=1');

Of course, posts do not normally have parent pages, so there will be no “current” classes assigned to that output when reading a post. Here is how to trick that function into thinking it is rendering the navigation for the “parent” category page.

//retrieve faux parent page dynamically… can skip and hard code in case 1
foreach(get_the_category() as $category) {
   $faux_parent_path = '/'.get_category_parents($category, FALSE, '/', TRUE);
}
$faux_parent_page = get_page_by_path($faux_parent_path)->ID;

//reset the post query as if on the faux parent page
query_posts('page_id='.$faux_parent_page);

//execute our "faked out" function
wp_list_pages('depth=1');

//reset the query back to the initial state
wp_reset_query();

If there are multiple elements that need be “tricked,” a best practice would be to put the “faux parent page” retriever at the top of the template, and declare it a global in any template files that need it. This would avoid repeated look ups of the faux parent page.

An Example: Seeing it All Put Together

A great example of a WordPress-powered CMS that pushes use case #2 to its limits can be seen at the home of m62 visual communications, at http://www.m62.net.

M62-pharm in Advanced Power Tips For WordPress Template Developers

All of the navigation items across the top (Presentation Theory, PowerPoint Slides, etc) are pages associated with post categories. The sub-navigation on the right contains sub-pages that are also associated with sub-categories. For example, in the screenshot above (available here), the visitor is on the “Pharmaceutical Templates” page (faux category), which is a child of the “PowerPoint Templates” page (also a faux category). The content starting with “Download free” (below the page title) is the content from the “Pharmaceutical Templates” page. The posts below the “Next Steps” bar, titled “Latest in Pharmaceutical Templates”, are the posts inside that category. The applicable related category is automatically discovered by the WordPress template, populating the category name “Latest in X” and recent posts. Now let’s look at one of the posts inside that category.

M62-post in Advanced Power Tips For WordPress Template Developers

Using the tips outlined above, the individual post retains the feel of being within the “Pharmaceutical Templates” page, right down to the breadcrumb navigation and “current” states in the navigation.

But not only does m62.net use category / page associations for most top and second level navigation items, it actually extends the concept to tags. The 5 “tabs” on the top right actually represent post tags, and each has a “tag page.”

Stay tuned!

The second part of the post will be published here, on Smashing Magazine, in two weeks. Hence, you may want to subscribe to our RSS-feed and follow us on Twitter. Any ideas or suggestions? Comment on this article!


© Jacob Goldman for Smashing Magazine, 2009. | Permalink | 35 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: , ,

Tags:

Fresh Free High-Quality Icon Sets


  

The most important aspect of designing an individual icon is that it has to be instantly recognizable, you have to know its function, and you need to know exactly what it is. If you are designing a set, the actual design becomes a lot harder, the designer has to face two initial challenges: each icon they design has to be individual and distinctive from the other, and, they also have to have similar features to show that they are related, completing the set. Not an easy task.

Perhaps that is why we love those small indispensible graphical images so much, it’s an appreciation of the hard work, creativity and talent of the designer. And to think, all those hours spent in front of a laptop crafting these little marvels, and then, allowing everyone else to download them for free. To all icon designers we say: “thank you”.

In this post we present a round-up of fresh high-quality icons that are available for free download and (sometimes only for personal) use. Please make sure to read license agreements before using icons in your designs – they can change from time to time.

You may be interested in the following related posts:

e-Commerce Icons

Money Back Guarantee Icon Set (registration is required)
100 % Money Back Guarantee Vector Icon Set. The set contains 3 versions: 30 day – 60 day and 90 day.

Money Back Guarantee Icon Set

Open Source Icons – (37signals)

Open Source Icons - (37signals)

10 Free High-Quality E-Commerce Icons

10 hochwertige, exklusive E-Commerce Icons

Credit Card Icons
22 Credit Card Icons that are perfect for your sites.

Useful Icons and Vectors

Daily Exhaust: Hand & Arrow Icons

Daily Exhaust: Hand & Arrow Icons

Free hand pointer icons

Royalty Free Icons and Stock Images

Webdesigner kit

Webdesigner kit

The Webdesigner Sketchup Icons

Webdesigner kit

Web Buttons Vector
Compilation of the free web button vectors and elements – useful for wireframing and prototyping!

Web Buttons Vector

Top 3 icons pack

Top 3 icons pack

500+ Free Vector Traffic Signs

500+ Free Vector Traffic Signs

Packaging Vector Pack
This Vector Freebie Pack is created by Ian Yates and is available exclusively from Vectortuts+. If your looking for high quality graphics to mock up your next client presentation with, then check out these packaging graphics.

Packaging Vector Pack

Exclusive Stationery Vector Pack
This new Vector Freebie Pack is created by Ian Yates. If you are looking for high quality graphics to mock up your next client presentation with, then check out these graphics.

Exclusive Stationery Vector Pack

Moderators Icons

Moderators Icons

How to be Green at Home

How to be Green at Home

Simple and Minimal icons

Free iPhone Toolbar Icons
Icons designed specifically for iPhone developers, available for free for anyone to use commercially under the Creative Commons Attribution 2.5 Canada license.

PixelPressIcons

Glyphish
Designed and carefully optimized for use on toolbars and tab bars in iPhone apps, these icons are also perfect for Android apps, websites, t-shirts, tattoos and more.

Glyphish

A travel and business vector pack

A travel & business vector pack

Token

Token

Standard Iconset by Templay

New Icon Sets

RRZE Icon Set

New Icon Sets

Characters so far
35 very original and eccentric characters.

New Icon Sets

Beautiful Icons

Philippe Starck Icons
Philippe Starck icons for Windows, Mac OSX, Linux.

Vase

Snow Leopard Icon
The new version of Mac OS X, Snow Leopard, was just released, so the designer decided to celebrate it with a new artwork. Download the Snow Leopard Wallpaper as well!

Snow Leopard

Billiardo 1

Billiardo 1

Moleskine Helvetica Icon

Moleskine Helvetica Icon

Foto Icon

Foto Icon

Free Cute Furry Monster Icons
“I’ve put together a little family of monsters, available for free download in the form of icons. Each monster can be found in PNG, ICNS and ICO filetypes for use on your Mac, PC or for inclusion in your website designs.”

Free Cute Furry Monster Icons

LiveJournal turns 10
Anniversary edition icons set, LiveJournal is celebrating its 10th Anniversary.

Royalty Free Icons and Stock Images

stratocaster Classic psd

stratocaster Classic psd

2001 Space Odyssey

Zyotism:Aesthetics

Vector Kitchen Icons
Vector Kitchen Icons – 25 different examples of kitchen stuff created in funny cartoon style. Set include: teapot, knifes, saucepan, pot, frying pan, plates, cups, microwave oven, forks, kitchen-range and so on. Soft gradients and colors, smooth contours, creative shapes.

Vector Kitchen Icons

Modern Chairs Icons

Modern Chairs Icons

Google Talk Icon

New Icon Sets

Chamber Orchestra

PixelPressIcons

Classic Cameras

Classic Cameras

Camera Nikon

Camera Nikon

Lollipop

Lollipop

Desktop & GUI Icon Sets

Gnome Icon Theme

Gnome Icon Theme

Alcohol

Alcohol

Generic Applications
This icon set is released under a special license which will allow software developers to use this set of 7 icons in their projects.

PixelPressIcons

Bevel and Emboss
Ever wondered how are all these glossy looking icons made? This is not a tutorial how to make them, as there is a lot of these out there, this is a fully editable PSD source you can download for free and use them for your projects (commercial and non-profit) or to see how this look is achieved.

Bevel And Emboss

32px icons set
A simple set of icons, available only in the resolution 32×32px, only in the iContainter format.

MacThemes

Windows 7 DVD-Box

Windows 7 DVD-Box

Xedia

Xedia

GiNUX
There are 64 icons in this set, all are 64×64px and available in both PNG. and ICO. formats.

New Icon Sets

Related Posts

You may be interested in the following related posts:


© Paul Andrew for Smashing Magazine, 2009. | Permalink | 118 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: , , ,

Tags:

Power Tips For WordPress Template Developers


 

With its latest releases, WordPress has extended its potential well beyond blogging, moving toward an advanced, robust and very powerful content management solution. By default, WordPress delivers a very lightweight, minimal system that offers only basic functionalities. But where the WordPress core falls short, there are a wealth of plug-ins that extend its limitations.

Plug-ins often offer simple solutions, but they are not always elegant solutions: in particular, they can add a noticable overhead, e.g. if they offer more functionality than needed. In fact, some general and frequently needed WordPress-functionalities can be added to the engine without bloated plugins, using the software itself.

This article presents 8 tips for WordPress template developers that address common CMS implementation challenges, with little to no plug-in dependence. These examples are written for WordPress 2.7+ and should also work in the latest WordPress-version.

You may be interested in the following related posts:

1. Associating pages with post categories

WordPress enables administrators to identify any page as the posts page: this is ideal for CMS implementations featuring a single news or blog feed. However, WordPress provides no simple, out-of-the-box mechanism to configure a site with multiple, independent feeds.

Here’s a common use case: a company wants a simple and casual blog, and a seperate and more formal feed for press releases inside their “About Us” section. Let’s list a few requirements mandated by a sample client seeking just that:

  • At no point should these two feeds be displayed as one.
  • Links to these feeds need to appear in page navigation.
  • The Press Release page needs to have static, maintainable content above its feed.
  • For SEO purposes, these feeds should have a page-like permalink structure: in other words, “mysite.com/category/press-releases” is unacceptable; the goal is “mysite.com/about-us/press-releases”.

The proposed sitemap

As is often the case, there are several approaches one can take. Major considerations used to guage the best approach include the number of standalone feed pages (one, in this case: Press Releases) and the necessity for a “primary” feed requiring multiple category support. For this example, let us assume that “Our Blog” does need to behave like a full featured blog with categories.

Preparing the site

This approach to “pages with single feeds” is built upon an association created between a page and a post category. The “primary” blog will simply be the “posts page” with a few template adjustments that will exclude posts from the “Press Releases” feed. To meet the SEO requirement for a logical and consistent URL structure, we will need to carefully configure and set permalinks.

  • In the “Reading” settings, ensure that the “Front page displays” option is set to “A static page”, and that the “Posts page” is set to “Our Blog”.
  • In the “Permalinks” settings for WordPress, ensure that “Custom Structure” is selected. The structure should be: /%category%/%postname%/.
  • In the page list, identify the the permalink (or slug) for the “About Us” page (using our example sitemap: let’s say “about-us”). Identify the slug for the Press Releases page (”press-releases”).
  • Two corresponding categories must be added: an “About Us” category with a matching permalink (”about-us”), and a “Press Releases” category with a matching permalink (”press-releases”) and its parent category set to “About Us”.
  • Create a post in the “Press Releases” category for testing purposes.

The proposed sitemap

Excluding a category from the blog page

To exclude a category from the main blog page (which shows all posts across categories), the post query used for the blog page template must be modified.

The WordPress codex outlines the solution. Simply identify the category ID for the “Press Releases” category (hovering the mouse over the category name in the admin panel and looking at the URL in the status bar is an easy way to find the ID - let’s use 5 for the example), and insert the following code above the post loop:

query_posts("cat=-5");

Note that many templates also include a list of categories in the sidebar, recent post lists, and other components that may not exclude posts from the “press releases” category. These will also need to be modified to exclude the category; this is easily supported by most WordPress calls.

Enabling the individual feed page

The feed page will require a custom page template. For this example, we named the template “Press Release Feed”, and used the generic “page.php” template as a starting point (copying it and renaming it “page_press.php”).

Since the requirements mandate static, editable page content above the feed, the first post loop - that drops in the page content - will be left as is. Below the code for page content output, another post query and loop will be executed. Once completed, the query should be reset using “wp_reset_query” so that items appearing after the loop - such as side navigation - can correctly reference information stored it the original page query.

The general framework for the code is below. The query posts documentation on the WordPress codex provides insight into great customization.

query_posts('category_name=Press Releases');
if ( have_posts() ) : while ( have_posts() ) : the_post();
	//post output goes here... index.php typically provides a good template
endwhile; endif;
wp_reset_query();

Of course, be certain to assign the “Press Releases” page the new template, in the page editor.

The devil is in the details

Depending on the characteristics of the individual site, many additional template customizations - beyond those outlined above - will probably be necessary. In particular, this “power tip” does not cover specific strategies for handling individual post views within these isolated feeds. At the high level, using conditional in_category checks within the “single.php” template (used for output of individual posts) should provide the foundation for customizing post views based on their category. If you are interested, a more detailed article may explore these strategies in greater detail (please let us know in the comments!).

Alternative Scenarios

Creating individual page templates for each standalone feed is an efficient solution for a site with only a couple of such feeds. There are, however, WordPress-powered sites like m62 visual communications that extend the idea of category and even tag association with pages much more deeply. m62 features dozens of pages associated with individual blog categories, parent categories, and tags, seamlessly mixed in with standard, “feed-less” pages. In these instances, a smarter solution would involve specialized templates that match tag and category permalinks against page permalinks to dynamically create associations.

This approach can also facilitate sites that require more than one “primary” (multi-category) blog, through the use of hierarchical categories / parent categories.

Again, if there is interest, a future article can discuss these methods in detail.

2. “Friendly” member only pages

Out-of-the-box, WordPress includes an option to designate any page or post as private. By default, these items do not show up in page or post lists (including navigation) and generate 404 errors when visited directly - unless the visitor is logged in. While utilitarian, more often than not, this is not ideal for usability.

Often times, sites intentionally make public visitors aware of pages or posts whose full content is only visible to members. A friendly message alerting visitors that they have reached a members-only page, with a prompt to log in, may be a better solution. Content-centric websites may tease the public with “above the fold” - or abbreviated - content for the entire audience, while enticing the visitor to log in or sign up to read the entire article.

Linedata's blog upsells with member exclusive content

This example offers a framework for these “hybrid” member / public pages using the latter scenario as an example. Content featured “above the fold” - or above the “more” seperator - will be visible to the general public. Content below the fold will only be available to members. In place of content below the fold, public visitors will be prompted to log in.

This approach to “hybrid” pages is built upon public, published pages with a custom field used to identify the page content as “member exclusive”.

  1. Create a page or post.
  2. Start with a paragraph or two visible to the general public.
  3. Insert the “more tag” at the end of the public content.
  4. Enter content visible only to logged in members below the more tag.
  5. Add a custom field named “member_content”. Set its value to 1.
  6. Publish the page with public visibility (the default).

Hybrid public / member content

The next step involves editing the applicable template files. Typically, this will be “page.php” (pages) and “single.php” (posts). Note that if these hybrid views will only apply to pages, a developer can create a “member content” page template as an alternative to using a custom field. Doing so will eliminate the need for the custom field check and alternative outputs inside the same template.

For this example, we shall assume that we created a post (not page) with member exclusive content. Therefore, we will need to edit “single.php”. Inside the template, find the the_content call used to drop in page and post content. Here’s what this often looks like before the changes:

the_content();

Here is the new code with the alternative “public” view:

if(!get_post_meta($post->ID, 'member_content', true) || is_user_logged_in()) {
    the_content('<p class="serif">Read the rest of this entry »</p>');
} else {
    global $more;	// Declare global $more (before the loop).
    $more = 0;	// Set (inside the loop) to display content above the more tag.
    the_content(""); //pass empty string to avoid showing "more" link
    echo "<p><em>The complete article is only available to members. Please log in to read the article in its entirely.</em></p>";
}

Combine this with the next tip to include a login form that sends members right back to the current page or post.

3. Embedding a log-in form that returns to the current location

Sometimes, sending members to the standard WordPress login form is not ideal. It may, for instance, not be consistent with the look and feel a client is seeking. There may also be instances where embedding a login form in a page - as in tip 7 - offers superior usability compared to clicking a link for the login page.

Museums in the Park, powered by WordPress, has a custom log-in form for members.

The code below drops the WordPress login form into the template, and sends the user back to the page they logged in from.

<?php if(!is_user_logged_in()) { ?>
	<form action="<?php echo wp_login_url(get_permalink()); ?>" method="post">
		<label for="log"><input type="text" name="log" id="log" value="<?php echo wp_specialchars(stripslashes($user_login), 1) ?>" size="22" /> User</label><br />
		<label for="pwd"><input type="password" name="pwd" id="pwd" size="22" /> Password</label><br />
		<input type="submit" name="submit" value="Send" class="button" />
		<label for="rememberme"><input name="rememberme" id="rememberme" type="checkbox" checked="checked" value="forever" /> Remember me</label>
	</form>
<?php } ?>

Be aware of a pitfall of this easy-to-implement power tip: if the user fails to login with the proper credentials, the log-in error will appear on the standard WordPress login form. The visitor will, however, still be redirected back to the original page upon successful log-in.

4. Identifying the Top Level Page

The “top level page” is the highest level page within the current branch of the sitemap. For example, if you consider the page below, you’ll find that “Support & Resources”, “Finding Support”, and “Support for Patients” all share the top level page “Support & Resources”.

The top level page is Support and Resources

There are some relatively new plug-ins that make “section”, or “top level page” WordPress navigation a cinch, such as Simple Section Navigation. However, there are plenty of instances (outside of navigation) where the template may need to be aware of the current top level page.

For instance, you many want to be able to style certain design elements, such as the navigation bar’s background image, depending on the currently chosen section. This can be achieved by checking the page ID of the top level page inside the header, and dropping in additional styles when the IDs for those top level pages were found.

Top level navigation changes its background image depending on the top level page

Here is how it works. Although WordPress offers no built in call to determine the top level page, it can be found with a single line of code in the template:

	$top_level = ($post->post_parent) ? end(get_post_ancestors($post)) : $post->ID;

Using a ternary conditional, this line of code checks the value of $post->post_parent, which returns the current page’s parent page ID, if one exists. If the conditional is evaluated as “true” (as any positive integer will), than the current page has some “ancestory”; in other words, it is inside of a page hierarchy or branch in the sitemap. If the conditional fails, the page is either a top level page, or not in any page ancestory (i.e. a post on a site without a blog “page” assigned).

If the current page has ancestory, an array containing the hierarchy “above” the page (parents, grandparents, etc) can be retrieved using the get_post_ancestors function. The last value in the array that function returns is always the ID of the top level page. Jump right to the last value using PHP’s end function. If the conditional fails (no ancestory), the code simply grabs the current page ID.

Keep in mind that, in many instances, this information is only useful when WordPress is working with an actual page (as opposed to a post, 404 page, etc). Therefore, this function and code that uses the top_level variable, may need to be wrapped inside a check that confirms that WordPress is loading a page: see the is_page() function.

5. Breadcrumb Navigation - without a plug-in

Example of a WordPress site with breadcrumb navigation

There are plenty of WordPress extensions that generate breadcrumb navigation. But you can actually create custom breadcrumb navigation with only a handful of lines of code in the template, opening up greater control and, potentially, less overhead. This approach to breadcrumbs builds on the get_post_ancestors function discussed in tip #4.

This tip won’t review formatting of breadcrumbs; for this example, the breadcrumbs will be dropped in an unordered bullet list. As it happens, lists of links tend to be a good format for search engines, and you can format them almost any way you like.

To start with, here is a basic implemenation of breadcrumbs that only deals with pages and includes a breadcrumb for “home” (the front page of the site) at the beginning of the list. Depending on the design of a particular template, some checks may need to placed around this code. In this example, it will be assumed that this code will be placed in the header.php template file, that the crumbs should appear only on pages, and that it should not show up on the front page. The current page and front page link will also be assigned special CSS classes for styling purposes.

if (is_page() && !is_front_page()) {
   echo '<ul id="breadcrumbs">';
   echo '<li class="front_page"><a href="'.get_bloginfo('url').'">Home</a></li>';
   $post_ancestors = get_post_ancestors($post);
   if ($post_ancestors) {
      $post_ancestors = array_reverse($post_ancestors);
      foreach ($post_ancestors as $crumb)
          echo '<li><a href="'.get_permalink($crumb).'">'.get_the_title($crumb).'</a></li>';
   }
   echo '<li class="current"><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
   echo '</ul>';
}

If the WordPress implementation has a static front page and has been assigned a “blog” page, one might want to show the breadcrumb path to the blog page. This can be accomplished by adding is_home() to the conditional check at the top:

if ((is_page() && !is_front_page()) || is_home()) {
   ...

The next evolution of this code involves the inclusion of breadcrumbs for individual category archives as well as individual posts. Note that WordPress allows posts to be assigned to multiple categories; to avoid making our breadcrumb trail unweildly, the script will simply grab the first category assigned to the post. For the sake of simplicity, the example will be assumed that hierarchical categories are not in play.

if ((is_page() && !is_front_page()) || is_home() || is_category() || is_single()) {
   echo '<ul id="breadcrumbs">';
   echo '<li class="front_page"><a href="'.get_bloginfo('url').'">Home</a></li>';
   $post_ancestors = get_post_ancestors($post);
   if ($post_ancestors) {
      $post_ancestors = array_reverse($post_ancestors);
      foreach ($post_ancestors as $crumb)
          echo '<li><a href="'.get_permalink($crumb).'">'.get_the_title($crumb).'</a></li>';
   }
   if (is_category() || is_single()) {
      $category = get_the_category();
      echo '<li><a href="'.get_category_link($category[0]->cat_ID).'">'.$category[0]->cat_name.'</a></li>';
   }
   if (!is_category())
      echo '<li class="current"><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
   echo '</ul>';
}

There are many ways to extend the breadcrumb navigation further. For instance, a developer might want breadcrumbs for different types of archives (tags, months, etc), or may incorporate hierarchical categories. While this article won’t walk through every possible implementation, the samples above should provide you with a solid framework to work with.

6. Creating sidebar content elements

Many websites feature distinct sidebars with common elements represented throughout the site, such as section navigation, contact information, and special badges (i.e. “Follow us on Twitter”). It is also common for sites to feature more basic HTML blocks in the sidebar that are associated with a single page, or several pages that may or may not be tied together in any logical way.

Some content management systems enable the idea of multiple content blocks out of the box. For instance, CitySoft Community Enterprise allows the editor to select from a variety of page layouts, some of which include multiple blocks of content that can be edited independently. This is convenient for some, though it does have some limitations: (1) it can be hard to integrate the prefabbed layout blocks into unusual areas in the overall site template, and (2), reusing some of these content blocks for multiple pages is not possible (without some additional, complicated custom development).

Here’s how to implement reusable “sidebar elements” in WordPress. For the sake of simplicity, this example assumes that only one sidebar element can be assigned to a page.

Fundamentally, these sidebar elements will simply be pages. Although non-essential, it can be a good organizational practice to create a page called “sidebars” that will contain all of the sidebar pages. Be careful to exclude this page in top level navigation and any other page lists or sitemaps. Sidebar elements are then constructed as “private” pages (so they cannot be searched or viewed independently by general visitors), with the “sidebar” container page set as the parent page. The title of the sidebar page will be used for the title of the sidebar element.

Editing a sidebar on the left; on the front end on the right

Once the sidebar has been created, the editor will need the ID of the sidebar page. The easiest way to find this is by rolling over the page title in the admin page list, and looking for the “id” in the URL (typically in the statusbar).

To assign the sidebar to a page, a new custom field is assigned to the page that will hold the sidebar called “sidebar”. The value for this field is the page ID of the sidebar page.

Now, in the sidebar template file (or wherever the sidebar element should appear), some code is included that checks for the custom field, and - if found - drops in the referenced page. To make the process of dropping the sidebar page content a bit more simple, the example will use the light weight plug-in, Improved Include Page. Here’s the code, which also drops “h2″ tags around the page title:

$sidebar_pg = get_post_meta($post->ID,'sidebar', true);
if (function_exists('iinclude_page') && $sidebar_pg) {
   include_page($sidebar_pg,'displayTitle=true&titleBefore=<h2>&titleAfter=</h2>

      &displayStyle=DT_FULL_CONTENT&allowStatus=publish,private');
}

7. Feature selected posts on the front page

Many CMS implementations feature some selected items from the blog feed on the home page, or even throughout the site in a sidebar or footer element. Content editors are, wisely, selective about what merits a front page mention. Here’s how to implement a selective blog feed that can be placed on a front page template or anywhere else in the design.

Featured news feed on front page

A special category is needed to classify posts as “Featured”; a category named “Featured” or “Front Page” is a good convention. For the content editor, marking a post as “featured” is as simple as adding it to this category (remember: posts can have multiple categories). On the template side, the ID of the “featured” category will be needed. The easiest way to find the category ID is by rolling over the category “edit link” inside WordPress administration and noting the ID in the URL (typically in the status bar).

Using this ID (”4″ in the example), and the number of posts to feature on the home page (let’s say three), the following code will list the featured posts beginning with the recent ones.

echo "<h3>Featured Blog Posts</h3>";
echo "<ul>";
$feat_posts = get_posts('numberposts=4&category=71');
foreach ($feat_posts as $feat) {
   echo '<li><a href="'.get_permalink($feat->ID).'">'.$feat->post_title.'</a></li>';
}
echo "</ul>";

As with the other examples, this code can be extended in a number of ways. For example, the SGE Corporation front page features the excerpt for the most recent item. The excerpt can be manually entered in the “excerpt” field or pulled automatically (if none is provided) by grabbing a certain number of characters from the beginning of the post’s content.

8. Highlight current post’s category

WordPress page lists assign special classes to each item, including classes that indicate whether a page is the current page, a parent page, an ancestor page, and so forth. Category lists do assign a special class (current-cat) to appropriate list items when the user is browsing a category’s archive. Unfortunately, categories do not, by default, get this special class assigned to them when the user is on a post inside the category. However, one can override this default limitation by grabbing the current category ID and passing it to the wp_list_categories function.

$category = get_the_category();
wp_list_categories('current_category='.$category[0]->cat_ID);

Note that there is one significant downside to this approach – only some category can be passed to the list categories function. So if a post is assigned to multiple categories, only the first category will be highlighted. However, if a site has distinct categories (say a news feed and an editorial feed), this can help a template developer treat the category more like a page navigation item.

Related posts

You may be interested in the following related posts:

About the author

Jake Goldman is Director of Client Services at C. Murray Consulting, a web development and strategy firm located in Providence, Rhode Island (USA). You can find his insights, development tips, and examples of his work on the company’s blog, or by following him on Twitter @jakemgold.


© Jacob Goldman for Smashing Magazine, 2009. | Permalink | 90 comments | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: , ,

Tags: