Mit seinem neuesten Releases, hat WordPress ihr Potenzial weit über Blogging erweitert, sich in Richtung einer fortschrittlichen, robust und sehr leistungsfähiges Content-Management-Lösung. Standardmäßig liefert WordPress eine sehr leichte, minimale System, das nur Grundfunktionen bietet. Aber wo das WordPress Core kurz fällt, gibt es eine Fülle von Plug-Ins, die ihre Grenzen erweitern.
Plug-ins bieten oft einfache Lösungen, aber sie sind nicht immer elegante Lösungen: vor allem, sie können einen spürbaren Aufwand hinzufügen, zB wenn sie mehr Funktionalität als benötigt wurden. In der Tat können einige allgemeine und häufig benötigte WordPress-Funktionalitäten, um den Motor ohne aufgeblähten Plugins hinzugefügt werden, mit Hilfe der Software selber.
Dieser Artikel stellt 8 Tipps für WordPress Template-Entwickler, die gemeinsamen Herausforderungen zu begegnen CMS-Implementierung, mit wenig bis gar kein Plug-In Abhängigkeit. Diese Beispiele sind für WordPress 2.7 + geschrieben und sollte auch in der neuesten WordPress-Version arbeiten.
Vielleicht interessiert Sie auch in den folgenden Related posts:
WordPress ermöglicht es Administratoren, beliebige Seite als Beiträge Seite zu identifizieren: das ist ideal für die CMS-Implementierungen kennzeichnen eine einzelne Nachrichten oder Blog-Feed. Allerdings bietet WordPress keine einfache, out-of-the-Box-Mechanismus, um eine Website mit mehreren unabhängigen Feeds konfigurieren.
Hier ist eine gemeinsame Nutzung Fall: Ein Unternehmen möchte eine einfache und Casual-Blog, und eine separate und mehr formale Feeds für Pressemitteilungen in ihren "Über uns". Lassen Sie uns ein paar Liste von Anforderungen einer Probe Client sucht nur so, dass Mandat:
Wie es oft der Fall ist, gibt es verschiedene Ansätze kann erfolgen. Wichtige Überlegungen verwendet, um den besten Ansatz cher Programmiersprache gehören die Anzahl der Standalone-Feed Seiten (ein, in diesem Fall: Pressemitteilungen) und die Notwendigkeit für eine "primäre", die mehrere Feed Kategorie Unterstützung. Für dieses Beispiel nehmen wir an, dass "Unser Blog" nicht brauchen, um wie ein voll ausgestatteter Blog mit Kategorien zu verhalten.
Dieser Ansatz der "Seiten mit Einzel-Feeds" basiert auf einer Verknüpfung zwischen einer Seite und einer post Kategorie erstellt gebaut. Der "primäre" Blog wird einfach die "Beiträge Seite" sein, mit ein paar Anpassungen, die Vorlage Beiträge aus den "Pressemitteilungen" Vorschub wird ausgeschlossen. Um die Forderung nach einer SEO logische und konsequente URL-Struktur gerecht zu werden, müssen wir sorgfältig konfigurieren und Permalinks.
Um eine Kategorie aus der Hauptseite des Blogs (zeigt alle Beiträge verschiedener Kategorien) auszuschließen, die Post-Abfrage für den verwendeten Blog-Seite Vorlage geändert werden muss.
Der WordPress Codex beschreibt die Lösung . Einfach identifizieren die Kategorie-ID für die "Presse"-Kategorie (die Maus über dem Namen der Klasse in der Admin-Panel und Blick auf die URL in der Statusleiste ist eine einfache Möglichkeit, um die ID zu finden - verwenden wir 5 für das Beispiel), und fügen Sie den folgenden Code oberhalb der Post-Schleife:
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.
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.
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!).
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.
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.
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”.
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:
<span>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>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.
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.
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.
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”.
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.
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 .
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><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><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><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><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.
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.
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');
}
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.
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.
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.
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.
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.
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!).
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.
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.
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”.
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:
<span>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>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.
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.
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.
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”.
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.
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 .
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><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><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><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><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.
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.
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');
}
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.
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.
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.
Great post. this is what I looking for, thanks
Thanks for article. Everytime like to read you.
Have a nice day
Joker
thanks
Thank you! I would now go on this blog every day!
Thanks
GlenStef
Hello Construction klooper in F7*&%^! classify of my english jer, buti danged keen re application .
I have a nice joke for you people!
Why is an evil witch like a candle? They are both WICKED
Great post. this is what I looking for, thanks
Thanks for article. Everytime like to read you.
Have a nice day
Joker
thanks
Thank you! I would now go on this blog every day!
Thanks
GlenStef
Hello Construction klooper in F7*&%^! classify of my english jer, buti danged keen re application .
I have a nice joke for you people!
Why is an evil witch like a candle? They are both WICKED