Tag: kranthi

HTML5 Semantics





 



 


Much of the excitement we’ve seen so far about HTML5 has been for the new APIs: local storage, application cache, Web workers, 2-D drawing and the like. But let’s not overlook that HTML5 brings us 30 new elements to mark up documents and applications, boosting the total number of elements available to us to over 100.

Sexy yet hollow demos aside, even the most JavaScript-astic Web 2.0-alicious application will likely have textual content that needs to be marked up sensibly, so let’s look at some of the new elements to make sure that your next project is as semantic as it is interactive.

To keep this article from turning into a book, we won’t look at each in depth. Instead, this is a taster menu: you can see what’s available, and there are links that I’ve vetted for when you want to learn more.

Along the way, we’ll see that HTML5 semantics are carefully designed to extend the current capabilities of HTML, while always enabling users of older browsers to access the content. We’ll also see that semantic markup is not “nice to have,� but is rather a cornerstone of Web development, because it is what enhances accessibility, searchability, internationalization and interoperability.

A human language like English, with its vocabulary of a million words, can’t express every nuance of thought unambiguously, so with only 100 or so words that we can use in HTML, there will be situations when it’s not clear-cut which element to use for which piece of content. In that case, choose one; be consistent across the site.

Some Presentational Elements Are Gone

Purely presentational elements such as center, font and big are now obsolete. Their role has been perfectly usurped by Cascading Style Sheets. Now, this doesn’t mean you have to rush out and recode all of those ancient pages; HTML5 makes them obsolete for authors, but because HTML5 strives not to break the Web, browsers will still render those cobwebbed legacy pages.

For the same reason, presentational attributes have been removed from current elements; for example, align on img, table, background on body, and bgcolor on table.

The evil frame element is absent in HTML5. Frames caused usability and accessibility nasties. If you get the urge to use them, use an older DOCTYPE so that your pages still validate.

Beyond this short overview, see the W3C’s exhaustive list of removed elements and attributes.

Some Presentational Elements Have Been Redefined To Be Semantic

Not all presentational elements have been taken out and shot. Some have undergone an extensive re-education program and emerged with shiny new semantics. For example, the small element no longer means “use a small font,� although it will display that way in browser style sheets. Now it represents side comments, such as small print:

Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.

Some of the redefinitions feel to me to be a mop-up. While I can get behind <b> for drawing attention to product names, keywords and so forth, without any special emphasis implied, specifying the semantics for marking up ship names (<i>, if you’re so inclined) feels weirdly precise. But I get seasick, and your nautical mileage may vary. With similar niche precision:

The u element [now] represents a span of text with an unarticulated, though explicitly rendered, non-textual annotation, such as labeling the text as being a proper name in Chinese text (a Chinese proper name mark), or labeling the text as being misspelt.

You can read more about changed elements and attributes on the W3C website.

Sexy New Semantics

We all know about video and audio. And canvas is particularly popular at the moment because it allows for 3-D graphics using webGL, so game designers can port their products to the Web. Like good ol’ img, these semantics are embedded content, because they drag in content from another source — either a file, a data URI or JavaScript.

Unlike img, however, they have opening and closing tags, allowing for fallbacks. Therefore, browsers that don’t support the new semantics can be fed some content: an image could be the fallback for a canvas, for example, or a Flash movie could be the fallback for video, a technique called “video for everybody.�

The source and track elements are empty elements (with no closing tags) that are children of video or audio.

The source element gets past the codec Tower of Babel that we have. Each element points to a different source file (WebM, MP4, Ogg Theora), and the browser will play the first one it knows how to deal with:

<audio controls>
  <source src=bieber.ogg type=audio/ogg>
  <source src=bieber.mp3 type=audio/mp3>
    <!-- fallback content: -->
    Download <a href=bieber.ogg>Ogg</a> or <a href=bieber.mp3>MP3</a> formats.
</audio>

In this example, Opera, Firefox and Chrome will download the Ogg version of Master Bieber’s latest toe-tappin’ masterpiece, while Safari and IE will grab the MP3 version. Chrome can play both Ogg and MP3, but browsers will download the first source file that they understand. The fallback content between the opening and closing tags is a link to download the content to the desktop and play it via a separate media player, and it is only shown in browsers that can’t play native multimedia.

For video, you could use an embedded Flash movie hosted on YouTube:

<video controls>
  <source src=best-video-ever.webm type=video/webm>
  <source src=best-video-ever.mp4 type=video/mp4>
    <!-- fallback content: -->
    <iframe width="480" height="360"
      src="http://www.youtube.com/embed/xzMUyqmaqcw?rel=0"
      frameborder="0" allowfullscreen>
    </iframe>
</video>

This way, users of older browsers, such as IE 6-8, will see a YouTube movie (as long as they have the Flash Player), so they will at least be able to see the video, while users with modern browsers will get the full native-video experience. Everyone gets the content, then, which is what your website is there for, after all.

The track element is a newer addition to the HTML5 family and is being implemented by Opera, Chrome and IE at the moment. It points to a subtitle file that contains text and timing information. When implemented, it synchronizes captions with the media file to enable on-demand subtitling and captioning; useful not only for viewers who are hard of hearing, but also for those who do not speak the language used in the audio or video file.

Semantics For Internationalization

Less woo! than the semantics for multimedia and games are the semantics for internationalization. It may surprise the cool kids in Silicon Valley to learn that a worldwide Web of people use languages other than English and even use different writing systems.

Languages such as Arabic and Hebrew are written right to left, unlike European languages, which are written left to right. On pages that use only one writing system, this doesn’t present a problem, but on pages with bi-directional (“bidi�) writing, browsers have to decide where to put punctuation, bullets, numbers and the like. Browsers usually do a pretty good job using the Unicode bidirectional algorithm, but it gets it wrong in some cases, which can seriously dent the comprehensibility of content.

HTML5 gives us a bdi element, which enables authors to override the Unicode bidirectional algorithm and make their text more comprehensible. For a further description of the problem and to see how bdi solves it, see “HTML5’s New bdi Element� by Richard Ishida, the W3C’s internationalization activity lead.

Some languages have scripts that are not alphabetic at all, but that express an idea rather than a sound. Occasionally, an author will have to assist readers with pronunciation for especially rare or awkward characters, usually by providing an alternate script in a small font above the relevant character. In print, this was traditionally done with a very small 5-point font called “ruby,� and HTML5 gives us three new elements for marking up ruby text: ruby, rt and rp.

For more information, see “The HTML5 ruby Element in Words of One Syllable or Less� by Daniel Davis.

Structural Semantics

Most people are aware that HTML5 gives us many new elements to describe parts of a Web page, such as header, footer, nav, section, article, aside and so on. These exist because we Web developers actually wanted such semantics. How did the authors of the HTML5 specification know this? Because in 2005 Google analyzed 1 billion pages to see what authors were using as class names on divs and other elements. More recently, in 2008, Opera MAMA analyzed 3 million URLs to see the top class names and top IDs used in the wild. These analyses revealed that authors wanted to mark up these areas of the page but had no elements to do so, other than the humble and generic div, to which they then added descriptive classes and IDs.

(HTML5 Doctor has many articles about HTML5 semantics, so we won’t bloat this article by going in depth here. Warning: some were written by me.)

The new semantics were built to degrade gracefully. For example, consider what the specification has to say about the new figure element:

The figure element represents some flow content, optionally with a caption, that is self-contained and is typically referenced as a single unit from the main flow of the document.

The element can thus be used to annotate illustrations, diagrams, photos, code listings, etc…

This isn’t a new idea. HTML3 proposed a fig element (which never made it into the final HTML 3.2 specification). It looked like this:

<FIG SRC="nicodamus.jpeg">
   <CAPTION>Ground dweller: <I>Nicodamus bicolor</I> builds silk snares</CAPTION>
   <P>A small hairy spider.
   <CREDIT>J. A. L. Cooke/OSF</CREDIT></P>
</FIG>

There’s a big problem with this. In browsers that do not support fig (and none do), the image wouldn’t be displayed because the fig element would be completely ignored. The contents of the credit element would be displayed, because it’s just text. So you’d get a credit with no image on older browsers.

In HTML5, you would code the same example like so:

<figure>
<img src="nicodamus.jpeg">
   <figcaption>
      <p>Ground dweller: <i>Nicodamus bicolor</i> builds silk snares.</p>
      <p>A small hairy spider.
      <small>J. A. L. Cooke/OSF</small&gt</p>
   </figcaption>
</figure>

Unlike the aborted HTML3 syntax, the HTML5 version is backwards-compatible: a browser that doesn’t “know� about the figure element will still show the img and the text inside figcaption (as the HTML3 credit element would similarly display its content). Note that we’re using the redefined small element, instead of minting a new credit element. Remember that “Small print is also sometimes used for attribution.�

HTML5 also gives us a new figcaption element. Originally, the specification’s authors tried to reuse caption, as suggested in HTML3, but there were legacy problems, because caption had previously only been a child of table.

One of the design principles on which HTML5 is based is that new features should degrade gracefully. When they can’t, the language allows for fallback content. It tries to reuse elements rather than mint new ones — but it’s a pragmatic language: when minting something new is necessary, it does so.

Interactive Semantics

The structural elements of HTML5 currently don’t do much in visual browsers, although software that sits on top of browsers (such as screen readers) are starting to use them (see “HTML5, ARIA Roles, and Screen Readers in March 2011“ and “JAWS, IE and Headings in HTML5.�)

Other elements do have a visual effect. The details element, for example, is a groovy interactive element that functions as “a disclosure widget from which the user can obtain additional information or controls.�

Most browsers will implement it as an “expando box�: when the user clicks on some browser-generated icon (such as a triangle or downwards-pointing arrow) or the word “Details� (which can be replaced by the author’s own rubric in a child summary), the element will slide open, revealing its details within. The details could be a full description of an image or graph, a description of a complex table, advanced options for a search form, or just about anything else. This is a common need on the Web today, now made native and obviating the need for custom JavaScript.

Most of us have seen HTML5’s new form semantics. Most of these are attributes of the input element, thereby ensuring graceful degradation to <input type=text> in older browsers. New elements include datalist, output, progress and meter.

Do We Have The Right Semantics?

So, we have many new semantics, but are they the right ones? After all, the Google research on which they were based was conducted in 2005 — quite some time ago! Perhaps the semantics are already somewhat behind the times? Many have noted that they’re document-centric rather than application-centric. Do we need more application-centered semantics, such as a login or share element, or some kind of modal element for modal dialogue boxes?

I don’t know; I’m not an app developer. But at least HTML is a “living standard,� and so these can be added if strong enough use cases are presented to the Working Group.

I think most coders would welcome a new way to embed images that respond to the device’s context. Borrowing from the video element, which displays source video according to what media queries instruct, I can imagine a new element such as picture:

<picture alt="angry pirate">
   <source src=hires.png media="min-width:800px">
   <source src=midres.png media="min-width:480px">
   <source src=lores.png>
      <!-- fallback for browsers without support -->
      <img src=midres.png alt="angry pirate">
</picture>

This would pull in hires.png for widescreen devices, midres.png for devices between 480 and 800 pixels wide, and lores.png for everything else, thereby rendering moot the question that designers currently ask themselves, “Do I make every browser download a high-resolution image and then squash it down for small screens, thus wasting bandwidth, or do I send a low-resolution image to every browser and scale it up for big screens, potentially sacrificing quality?�

Taking a leaf from the other popular semantics we’ve seen, there would be a fallback in the middle — in this case, a conventional img element — so everyone would get the right content.

Sending the right-sized image to devices without wasting bandwidth is one of the knottiest problems in cross-device and responsive design at the moment. Perhaps we’ll see a solution to this in HTML6. At the moment, the best solutions, which include Matt Wilcox’s Adaptive Images and Filament Group’s Responsive Images, require JavaScript and tweaks to the server’s htaccess file. The worst solutions require old-fashioned techniques, such as browser-sniffing, now rebranded as “device detectionâ€� but still the same old user-agent string-pattern matching, which is hilariously fragile, not future-proof or scalable, and straight out of the days of “Best viewed in Netscape Navigator at 800 × 600â€� badges on websites.

When, Where, Who?

A lot of data depends on three pieces of information: when, where and who?

HTML5 Semantics

HTML5 has a time element (which has been a bit of a battleground lately). This enables you to annotate a human-readable date with an unambiguous machine-readable one. It doesn’t matter what goes between the tags, because that’s the content for people to read. So, you could use either of the following:

<time datetime="1982-07-18">The day the woman I love was born</time>

<time datetime="1982-07-18">Priyanka Chopra’s birthday</time>

Whichever you choose, the machine would still know the date you mean because of the datetime attribute, formatted as YYYY-MM-DD. If you wanted to add a time, you could: separate the time from the date with a T, and then put the time in 24-hour format, terminated by a Z, along with any time-zone offset. So, 2011-11-13T20:00Z would be 8:00 pm on 13 November 2011 UTC, while 2011-11-13T23:26.083Z-05.00 would be 23:26 pm and 83 milliseconds in the time zone lying 5 hours before UTC. A Sri Lankan-localised browser could use this information to automatically convert dates into Buddhist calendar. Search engines could use timestamps to help evaluate “freshness”.

It’s perhaps surprising that, even though geo-location is so prevalent now, we don’t have a location element that simply takes three attributes: latitude, longitude and (optionally) altitude. It would be great to be able to write the following:

<location lat=51.502064 long=-0.131981>London SW1A 4WW</location>

The browser would then offer to show you a map or give you directions from the current GPS location or any other location-based service.

(Since I gave the talk that this article is based on, Ian Hickson, the HTML5 editor, said that he expects to add a new element. If I could choose, I’d prefer , so I could wear a T-shirt with the slogan “I’ve got the time if you’ve got the place“.)

HTML3 had a person element, “used for names of people to allow these to be extracted automatically by indexing programs,â€� but it was never implemented. In HTML4, the cite element could be used to wrap names of people, but this has been removed in HTML5 — controversially (see “Incite a Riotâ€� by Jeremy Keith). In HTML5, then, we’re left with no way to unambiguously denote a person. People’s names are, however, a hard problem to solve. Whereas times and dates have well-known standardized ISO formats (YYYY-MM-DD and HH:MM:SS.mmm, respectively), and location is always latitude, longitude and altitude, personal names are harder to break down into useful parts: there are Russian patronymics, Indonesian single-word names, multiple family names, and Thai nicknames to consider. (See Richard Ishida’s excellent article “Personal Names Around the Worldâ€� for more information and discussion.)

The new data element, which replaces time, has a value attribute that passes machine-readable information, but it has no required or implied format, so there is no way for a browser or search engine to know, for example, whether 1936-10-19 is a date, a part number or a postal code.

Microdata

HTML5, like HTML4, is extensible (but not in the oh-so-dirty eXtensibility way of XML formats, so loathed by the Working Group). You can use the tried and tested microformats, which use HTML classes, or the full RDFa specification, which doesn’t validate in HTML4 or HTML5. Because RDFa was considered to be too hard for authors to write (Google has conducted research that finds that authors make 30% more mistakes with RDFa than with other formats), HTML5 specifies microdata, a mechanism for adding common semantics via agreed-upon markup patterns. HTML5 Doctor has more information on HTML5 microdata, and Opera 11.60 supports the Microdata DOM API.

Like microformats and RDFa, the extra semantics added to the markup make sense only if you have a cheat sheet that tells you what each piece means. This means that the data has to point to a vocabulary that tells any crawler how to interpret the lump of data it finds. For microdata, there is the newly established Schema.org, which is “a collection of schemas, i.e. HTML tags, that webmasters can use to mark up their pages in ways recognized by major search providers.�

Do Semantics Matter Anyway?

Now that more and more markup is generated by JavaScript, some people are tempted to think that semantics don’t matter. We see various products marketed as HTML5 which simply make div‘s fly around the screen with JavaScript  —  simple DHTML techniques unchanged from 10 years ago.

I’ve even seen some Web pages with no markup at all. Some frameworks emit skeletal HTML with empty body tags and inject all the HTML with script. If you’re squirting some minified JavaScript down the wire, with no markup at all, you’re closer to Flash than you are to the Web.

In the same way that 47 minutes is (apparently) too long to to struggle making a CSS layout, at which point you should just give up and use tables, some people suggest that thinking about which element to use is a waste of time. “There are two types of developers: those who argue about div’s not being semantic and those who create epic shit” writes Thomas Fuchs, as if the two activities were mutually exclusive.

A better argument is that no software cares about or consumes semantics anyway, so why bother? This isn’t true (work is underway already to map assistive technologies to new semantics), but even if it were true, it ignores that this is a chicken-and-egg argument. It assumes that no new search engine will ever come to the market and be able to use new elements, or that browsers will never release new versions that can make use of these semantics, asnd that developers will write no new extensions  —  in short, it assumes that the evolution of the Web is complete.

Semantics do matter. Semantics communicate meaning, and once that is established, machines can do something meaningful with that data, without having to develop and use algorithms to guess. A browser extension might allow a user to jump straight to the nav with a single keystroke. It can do this because it looks for nav rather than having to employ heuristics to find a div with an id or class that would suggest it’s being used as navigation (assuming the author decided to use something sensible like nav, navigation, sidebar, or menu  —  and a restaurant site with a div called “menu” might be a list of foods rather than other pages…ah, the ambiguity of natural language). A crawler might dynamically assemble articles on a timeline. There are many more possibilities than my meagre imagination can dream up.

The Web is based on simple technologies, mashed up together to bring surprising results  —  results which have certainly surpassed the inventors’ original intents or expectations. The Web will continue to do so. What makes the Web so great, so flexible and so powerful is the fact that content is in open formats that can be parsed and mashed up in new and surprising ways.

These can happen if the content is marked up for meaning by the author  —  and if the language has the right markup elements for authors to use as a vocabulary. HTML5 extends our vocabulary. We’ll need more words  —  and those will come about with HTML6 etc.

If, like me, you believe the Web to be a system that works across browsers, across operating systems, across devices, across languages, that is View-sourcable, hackable, mash-uppable, accessible, indexable, reusable, then we need to ensure that we use the small number of semantic tools at our disposal properly, and we’ll all benefit.

(This article is based on a talk I gave at the Fronteers Conference.)

About the Author

Bruce evangelizes Open Web Standards for Opera. He wrote the book Introducing HTML5 together with Remy Sharp. The book points out the good and bad parts of HTML5 specifications and shows you how to use the language as well as some areas of spec will be discussed theoretically as they’re not yet implemented anywhere. It’s the first full-length book on HTML5 (New Riders, appearing in the 2nd edition).

(al) (il) (vf)


© Bruce Lawson for Smashing Magazine, 2011.


WordPress Multisite: Practical Functions And Methods





 



 


Multisite is a powerful new feature that arrived with the release of WordPress 3.0. It allows website managers to host multiple independent websites with a single installation of WordPress. Although each “website� in a network is independent, there are many ways to share settings, code and content throughout the entire network.

WordPress Multisite

Since the beginning of the year, I’ve been developing themes and plugins for a WordPress Multisite-powered content network. During that time I’ve learned many powerful tips and tricks unique to Multisite. This guide will introduce you to a few Multisite-specific functions, along with real-world programming examples that you can begin using today. Hopefully, it will open your eyes to a few of the new possibilities available in Multisite.

Why Use Multisite?

Multisite is a great option for freelancers, businesses and organizations that manage multiple WordPress websites. Whether you’re a freelancer who wants to provide hosting and maintenance to clients, a college organization looking to centralize the management of your websites, or a large news publisher trying to isolate silos for different departments, Multisite is the answer.

Managing multiple websites with a single installation of WordPress enables you to easily upgrade the core, plugins and themes for every website in a network. You can share functionality across multiple websites with network plugins, as well as standardize design elements across multiple websites using a parent theme.

Overview of Benefits

  • Users are able to easily access and manage multiple websites with a single user account and profile.
  • Users can access a particular website or every website using the same account.
  • Information from one website can be completely isolated from others.
  • Information from one website can be easily shared with others.
  • Theme functionality can be shared across multiple websites using a parent-child theme relationship or a functionality plugin.
  • Updates and upgrades can be rolled out across multiple websites in less time, reducing overhead and maintenance costs.
  • Customizations to WordPress can be efficiently distributed in a centralized, cascading method using network-wide plugins.

I won’t explain how to install and configure Multisite. If you need help, plenty of great articles are available in the WordPress Codex.

Working With Multisite Functions

Multisite-enabled WordPress installations contain additional functions and features that theme developers can use to improve the experience of a website. If you find yourself developing themes and plugins for WordPress Multisite, consider the following tips to customize and improve the connectivity of the network.

Displaying Information About a Network

You might find yourself in a situation where you would like to display the number of websites or users in your network. Providing a link to the network’s primary website would also be nice, so that visitors can learn more about your organization.

Multisite stores global options in the wp_sitemeta database table, such as the network’s name (site_name), the administrator’s email address (admin_email) and the primary website’s URL (siteurl). To access these options, you can use the get_site_option() function.

In this example, I’ve used the get_site_option() function along with get_blog_count() and get_user_count() to display a sentence with details about a network.

<?php if( is_multisite() ): ?>

   The <?php echo esc_html( get_site_option( 'site_name' ) ); ?> network currently powers <?php echo get_blog_count(); ?> websites and <?php echo get_user_count(); ?> users.

<?php endif; ?>

This small snippet of code will display the following HTML:

The Smashing Magazine network currently powers 52 websites and 262 users.

Many useful Multisite functions can be found in the /wp-includes/ms-functions.php file. I highly suggest browsing the Trac project yourself. It’s a great way to find new functions and to become familiar with WordPress coding standards.

Build a Network Navigation Menu

Many networks have consistent dynamic navigation that appears on all websites, making it easy for visitors to browse the network. Using the $wpdb database class, along with the get_site_url(), home_url(), get_current_blog_id(), switch_to_blog() and restore_current_blog() functions, we can create a fully dynamic network menu, including a class (.current-site-item) to highlight the current website.

The SQL query we’ve created in this example has the potential to become very large, possibly causing performance issues. For this reason, we’ll use the Transients API, which enables us to temporarily store a cached version of the results as network website “transients� in the sitemeta table using the set_site_transient() and get_site_transient() functions.

Transients provide a simple and standardized way to store cached data in the database for a set period of time, after which the data expires and is deleted. It’s very similar to storing information with the Options API, except that it has the added value of an expiration time. Transients are also sped up by caching plugins, whereas normal options aren’t. Due to the nature of the expiration process, never assume that a transient is in the database when writing code.

The SQL query will run every two hours, and the actual data will be returned from the transient, making things much more efficient. I’ve included two parameters, $size and $expires, allowing you to control the number of posts returned and the expiration time for the transient.

One of the most powerful elements of this example is the use of switch_to_blog() and restore_current_blog(). These two Multisite functions enable us to temporarily switch to another website (by ID), gather information or content, and then switch back to the original website.

Add the following to your theme’s functions.php file:

/**
 * Build a list of all websites in a network
 */
function wp_list_sites( $expires = 7200 ) {
   if( !is_multisite() ) return false;

   // Because the get_blog_list() function is currently flagged as deprecated
   // due to the potential for high consumption of resources, we'll use
   // $wpdb to roll out our own SQL query instead. Because the query can be
   // memory-intensive, we'll store the results using the Transients API
   if ( false === ( $site_list = get_transient( 'multisite_site_list' ) ) ) {
      global $wpdb;
      $site_list = $wpdb->get_results( $wpdb->prepare('SELECT * FROM wp_blogs ORDER BY blog_id') );
      // Set the Transient cache to expire every two hours
      set_site_transient( 'multisite_site_list', $site_list, $expires );
   }

   $current_site_url = get_site_url( get_current_blog_id() );

   $html = '
    ' . "\n"; foreach ( $site_list as $site ) { switch_to_blog( $site->blog_id ); $class = ( home_url() == $current_site_url ) ? ' class="current-site-item"' : ''; $html .= "\t" . '
  • ' . get_bloginfo('name') . '
  • ' . "\n"; restore_current_blog(); } $html .= '
' . "\n\n"; return $html; }

(Please note: The get_blog_list() function is currently deprecated due to the potential for a high consumption of resources if a network contains more than 1000 websites. Currently, there is no replacement function, which is why I have used a custom $wpdb query in its place. In future, WordPress developers will probably release a better alternative. I suggest checking for a replacement before implementing this example on an actual network.)

This function first verifies that Multisite is enabled and, if it’s not, returns false. First, we gather a list of IDs of all websites in the network, sorting them in ascending order using our custom $wpdb query. Next, we iterate through each website in the list, using switch_to_blog() to check whether it is the current website, and adding the .current-site-item class if it is. Then, we use the name and link for that website to create a list item for our menu, returning to the original website using restore_current_blog(). When the loop is complete, we return the complete unordered list to be outputted in our theme. It’s that simple.

To use this in your theme, call the wp_list_sites() function where you want the network menu to be displayed. Because the function first checks for a Multisite-enabled installation, you should verify that the returned value is not false before displaying the corresponding HTML.

<?php
// Multisite Network Menu
$network_menu = wp_list_sites();
if( $network_menu ):
?>
<?php echo $network_menu; ?>
<?php endif; ?>

List Recent Posts Across an Entire Network

If the websites in your network share similar topics, you may want to create a list of the most recent posts across all websites. Unfortunately, WordPress does not have a built-in function to do this, but with a little help from the $wpdb database class, you can create a custom database query of the latest posts across your network.

This SQL query also has the potential to become very large. For this reason, we’ll use the Transients API again in a method very similar to what is used in the wp_list_sites() function.

Start by adding the wp_recent_across_network() function to your theme’s functions.php file.

/**
 * List recent posts across a Multisite network
 *
 * @uses get_blog_list(), get_blog_permalink()
 *
 * @param int $size The number of results to retrieve
 * @param int $expires Seconds until the transient cache expires
 * @return object Contains the blog_id, post_id, post_date and post_title
 */
function wp_recent_across_network( $size = 10, $expires = 7200 ) {
   if( !is_multisite() ) return false;

   // Cache the results with the WordPress Transients API
   // Get any existing copy of our transient data
   if ( ( $recent_across_network = get_site_transient( 'recent_across_network' ) ) === false ) {

      // No transient found, regenerate the data and save a new transient
      // Prepare the SQL query with $wpdb
      global $wpdb;

      $base_prefix = $wpdb->get_blog_prefix(0);
      $base_prefix = str_replace( '1_', '' , $base_prefix );

      // Because the get_blog_list() function is currently flagged as deprecated
      // due to the potential for high consumption of resources, we'll use
      // $wpdb to roll out our own SQL query instead. Because the query can be
      // memory-intensive, we'll store the results using the Transients API
      if ( false === ( $site_list = get_site_transient( 'multisite_site_list' ) ) ) {
         global $wpdb;
         $site_list = $wpdb->get_results( $wpdb->prepare('SELECT * FROM wp_blogs ORDER BY blog_id') );
         set_site_transient( 'multisite_site_list', $site_list, $expires );
      }

      $limit = absint($size);

      // Merge the wp_posts results from all Multisite websites into a single result with MySQL "UNION"
      foreach ( $site_list as $site ) {
         if( $site == $site_list[0] ) {
            $posts_table = $base_prefix . "posts";
         } else {
            $posts_table = $base_prefix . $site->blog_id . "_posts";
         }

         $posts_table = esc_sql( $posts_table );
         $blogs_table = esc_sql( $base_prefix . 'blogs' );

         $query .= "(SELECT $posts_table.ID, $posts_table.post_title, $posts_table.post_date, $blogs_table.blog_id FROM $posts_table, $blogs_table\n";
         $query .= "\tWHERE $posts_table.post_type = 'post'\n";
         $query .= "\tAND $posts_table.post_status = 'publish'\n";
         $query .= "\tAND $blogs_table.blog_id = {$site->blog_id})\n";

         if( $site !== end($site_list) )
            $query .= "UNION\n";
         else
            $query .= "ORDER BY post_date DESC LIMIT 0, $limit";
      }

      // Sanitize and run the query
      $query = $wpdb->prepare($query);
      $recent_across_network = $wpdb->get_results( $query );

      // Set the Transients cache to expire every two hours
      set_site_transient( 'recent_across_network', $recent_across_network, 60*60*2 );
   }

   // Format the HTML output
   $html = '


';

   return $html;
}

Using this function in your theme is simple. Be certain to check the return value before outputting HTML to avoid conflicts with non-Multisite installations.

<?php
// Display recent posts across the entire network
$recent_network_posts = wp_recent_across_network();
if( $recent_network_posts ):
?>
<?php echo $recent_network_posts; ?>
<?php endif; ?>

Retrieve a Single Post from Another Website in the Network

In certain situations, you may find it useful to refer to a single page, post or post type from another website in your network. The get_blog_post() function makes this process simple.

For example, you may want to display the_content() from an “About� page on the primary website in your network.

<?php
// Display "About" page content from the network's primary website
$about_page = get_blog_post( 1, 317 );
if( $about_page ):
?>
<?php echo $about_page->post_content; ?>
<?php endif; ?>

Did you notice that the entire $post object is returned? In this example, we’ve used only the_content(), but far more information is available for other circumstances.

Set Up Global Variables Across a Network

Starting any WordPress project in a solid local development environment is always important. You might find it handy to have a global variable that determines whether a website is “live� or “staging.� In Multisite, you can achieve this using a network-activated plugin that contains the following handy function, assuming that your local host contains localhost in the URL:

/**
 * Define network globals
 */
function ms_define_globals() {
   global $blog_id;
   $GLOBALS['staging'] = ( strstr( $_SERVER['SERVER_NAME'], 'localhost' ) ) ? true : false;
}
add_action( 'init', 'ms_define_globals', 1 );

When would you use this $staging variable? I use it to display development-related messages, notifications and information to improve my workflow.

Display the Page Request Information in a Local Environment

I use the $staging global variable to display the number of queries and page-request speed for every page across a network in my local environment.

/**
 * Display page request info
 *
 * @requires $staging
 */
function wp_page_request_info() {
   global $staging;
   if ( $staging ): ?>
      <?php echo get_num_queries(); ?> queries in <?php timer_stop(1); ?> seconds.
   <?php endif;
}
add_action( 'wp_footer', 'wp_page_request_info', 1000 );

This is only one of many ways you can use the ms_define_globals() function. I’ve used it to define, find and replace URLs in the content delivery network, to detect mobile devices and user agents, and to filter local attachment URLs.

Conclusion

There is tremendous value in the simplicity of managing multiple websites in a single installation of WordPress. Leveraging WordPress Multisite is quickly becoming a requisite skill among WordPress developers. These techniques should provide a solid foundation for you to build on, so that you can be the next WordPress Multisite theme rock star!

Other Resources

(al)


© Kevin Leary for Smashing Magazine, 2011.


Screen readers and CSS

As I have noted in a couple of blog posts recently, there are some cases when CSS has quite unexpected results in screen readers (or the way web browsers create the accessibility information they hand over to screen readers). If you haven’t read them, the posts are Screen readers, list items and list-style:none and Using display:table has semantic effects in some screen readers.

Here are a few examples:

  • Using display:table on non-table elements to get the visual layout characteristics of an HTML table without actually using one may cause screen readers to act as if there was a real table
  • Using display:block or float on table-related elements may cause screen readers to treat the table as a layout table and ignore its semantics or report an incorrect data structure
  • Using list-style:none to visually remove bullets or numbers from list items may cause screen readers to ignore them too, basically treating list items as paragraphs of text

Read full post

Posted in , .

Copyright © Roger Johansson



Fluidity Of Content And Design: Learning From Where The Wild Things Are





 



 


Have you read Where the Wild Things Are? The storybook has fluidity of content and design figured out.

It goes that one night, protagonist Max “wore his wolf suit and made mischief of one kind or another.� He hammers nails into walls, pesters a small dog. Author Maurice Sendak doesn’t explain these hijinks textually for the reader. The mischievous acts are illustrated on the right-hand pages. Readers make the narrative connections for themselves.

Wild Things Book
Photo of the book Where the Wild Things Are

The words and pictures depend on each other for completeness. Web designers can employ the same complementary dependence of graphic and text in their own work. It encourages a sense of belonging and can create strong first impressions, which are often essential to effective Web design. Because Web design is not confined to page-by-page display as storybooks are, we’ve got no excuse for neglecting Curt Cloninger’s assertions that a design “has to somehow be relevant to the content, accurately representing its purposes in the medium,� and that “the content has to be useful to the site’s audience.�

This post explains four strategies for improving fluidity of content and design, and we’ll gauge the effectiveness with which several websites use these strategies, taking special note of what we can learn from Sendak’s Where the Wild Things Are.

With Graphics As Your Witness

When editing critical papers during my undergrad, I was constantly mindful of backing up every claim I made in writing. Describing a protagonist as “yearning for a return to childhood� wasn’t enough to convince a professor unless I could refer to a passage where this was suggested.

Though published way back in 1997, Jakob Nielsen’s analysis in “How Users Read the Web� still offers a storehouse of relevant advice about how users gauge legitimacy online. He suggests that when businesses use promotional language online, they create “cognitive burdens� on their users, slowing down their experience with the website, triggering a filter by which they weigh fact against fiction.

Instead, use design to complement or convey self-promotion, easing user skepticism from the get-go.

Makr Carry Goods effectively “backs up� its content with graphics to convince users of the “news�-worthiness of its work. In the example below, the visual promotion of the products complements the text: without having to scroll over the images, we see the products themselves as being the news.

Makr Home

Scrolling over the images on top reveals the textual “news�:

Makr Hover

From there, users can carry on their visual journey through the Mark Carry catalogue, enticed to read on by the persistent connection between the product and the news section, a connection that compels users to explore further.

Key to this graphic-textual connection is the visual quality of the products themselves. Without the clean white presentation and professional style, the visuals here might fail to suggest a connection with the news. But the products have been presented to impress.

Without engaging visual confirmation, content will often fail to persuade.

Take Mark Hobbs’ professional website:

Mark Hobbs

He claims that he’s “not normal.� He’s “extraordinary… adaptable, loyal, ambitious and an Eagle Scout,� and he’s “like a sponge� (among other things). If he were getting points for descriptiveness, Hobbs would take first place. But he’s got no visual evidence of any of these claims. No hint at this lack of normalcy.

Besides, as Nielsen’s studies suggest, users generally dislike “marketese�: writing that is boastful, self-promotional and full of subjective claims. Then again, should claiming not to be normal be considered a boast?

Mark’s claims could have been justified by an impressive and immediate visual display of his past work. Engaging users with the strict facts of his expertise could have reinforced his textual claims.

Consider the home page of Rally Interactive:

Rally

It is “here to help you build digital things.� We know this because of the two immediate examples of its work, presented in triangles that recall other projects that required exceptional skill: the pyramids.

Rally’s folio effectively demonstrates a strategy of fluid content and design. The firm backs up its claim and provides users with an immediately useful and positive association. The visual and verbal prompts coalesce to convince users of Rally’s expertise.

Going back to Where the Wild Things Are, if Sendak hadn’t included visuals of Max’s misdoings, what sympathy could we gain for him as his mother sends him up to bed? We can interpret his “mischief� any way we choose, but Sendak’s visual direction helps us gauge what kind of protagonist (or antagonist) Max will be for the remainder of the story. Verbal prompts simply wouldn’t cut it.

Fluid content and design reduce the user’s search time and, in this case, justify the claims made textually. Users don’t have the time or willingness to hunker down and read, particularly when looking for a service. Fluid content and design convince users of the truth of a claim before they even begin to question it.

Tighten Up

Once you’ve eliminated any refutable claims, you might find your content looking a bit sparse. In fact, you want it naked: easy to scan and to the point.

Christine Anameier’s article “Improving Your Content’s Signal-to-Noise Ratio� points us in the right direction for creating tight content that isn’t afraid to depend on suggestive design to share the workload.  There will always be information that the user cannot process visually. So, what should you put in text?

Anameier suggests segmentation, prioritization and clear labeling to make the most of your content.

Segmentation

Segmentation entails sectioning content on the page according to audience or task.

The home page for Jessica Hische’s design portfolio does this effectively:

Jessica Hische

The home page targets the specific needs of users. Hische has divided the links to her services according to what particular users will be looking for, sparing us long descriptions of each service.

Hische also spares us a textual description of the quality of her service, instead pairing tight layout of text with sprawling, confident design. We can gather from the background a sense that she has clean organization. The orange ribbon font “welcomes� us and puts us at ease so that the text doesn’t have to.

Prioritization

Prioritization, as Anameier says, requires that you “understand your audiences and their tasks, and decide what your website is trying to do.� Structure your website to reflect these tasks, removing any content that strays from the path. Hische’s home page demonstrates a comprehension of her users’ purpose for visiting the website, and it wastes no words.

Content and design fluidity entails deciding what should be explained textually and what should be demonstrated graphically. Hische does not verbally boast about her quality of service. The design does that for her, conveying an array of positive attributes, from classic taste to proficient organization.

Hische recognizes that the first priority of users is not whether she’s any good, but whether she offers what they need. Once that is clarified, users will look into the quality. Keyword: look.

Creating those fluid user experiences in which content and design cohere requires, as Mark Boulton states in “A Richer Canvas,� “text that feels connected to the physical form in a binding manner that should make it invisible.� Anameier herself says that incorporating “specific and accurate link text, page titles and headings� gives users the luxury of perusing graphic elements on the page without being disrupted by navigation obstacles.

Labeling

Labeling that is structured with the user’s goals in mind will be trim and to the point, “invisible,� as Boulton suggests, so that the visual showcase enjoys some attention, too.

Tight content that follows Anameier’s guidelines will visually suggest your service’s qualities and attributes strongly. The description of the service itself will rely heavily on text, but what sets your service apart from others can be conveyed visually. Creating cohesive visual and textual discovery paths for users replicates that same sense of control that users get from the storybook.

Doodle Pad superbly utilizes segmentation, prioritization and clear labeling on its “About� page:

Doodle Pad

Carrying over the sketch-book theme to its visuals, Doodle Pad sets down user goals with clarity, displaying information directed at clients and creative professionals.

The labelling is clear and styled with familiar doodling motifs that show the user where to look for what they need. Key questions are answered, and the word count is not too shabby for a software concept.

Impressively, Doodle Pad connects the imagery and layout to the overall concept without over-informing or weighing down users with elaborate language. It gives us notebook-style notes for a notebook concept: tight and user-friendly.

Check The Narrative Voice

Curt Cloninger’s article “A Case for Web Storytelling� argues for narrative voice as being an essential consideration for Web designers who want to create engaging user experiences.

Designers are at a great advantage when it comes to synthesizing text with graphics. We can create a rich narrative tone that convinces and directs users. We are able to explore and experiment with the Web’s possibilities, going beyond Where the Wild Things Are and celebrating non-linear narratives, incorporating several kinds of interactive media.

With Web design, narrative voice need not stay put in the text. It’s more flexible that in storybooks, and Cloninger encourages us to play with that.

For instance, look at the layout for MailChimp 5.2. Toying with slogans that would look out of date on another Web page, the designers evoke nostalgia with their use of background images, color and typography, elements ripe with narrative potential:

Mail Chimp Retro

Viewers interpret the slogans the right way because of the text’s ironic connection to the design. The “real people behind all those email addresses,� is a wink from the designers, because the viewers recognize that the “real people� in the background don’t look very “real� at all.

Users will commit to a fluid narrative online if the design fully commits to the content. And as Cloninger says, using narrative voice through Web design presents countless possibilities for exploration.

MailChimp explores one such possibility with its demo video, complete with more “wholesome� design and content:

Mail Chimp Retro 2

Users can expect to be led on this retro journey through the other formats for narrative voice, as the video suggests with its old-school film-reel introduction.

The narrative voice is so woven into the content and design that MailChimp 5.2 could offer all kinds of 1950s-terrific claims and users would be moved to follow along.

MailChimp 5.2 experiments with tailoring content and design to a narrative voice, but it is effective because of its consistency. If it hadn’t committed to a particular narrative style, then the escapist spell of this user experience would have been broken.

Green Tea Design

Green Tea Design has chosen a watery, traditional Japanese-inspired design for its website. A geisha shades herself with an umbrella, looking down meekly, making for a quiet non-confrontational effect. But look at the aggressive text: “We don’t design wimpy websites that get sand kicked in their face by the competition.� The text goes on the offence, but the design doesn’t align with or enhance the narrative voice.

Try this: choose one adjective with which you’d like users to describe your website. Affix a sticky note of this adjective to the top of your monitor, and measure every sentence on your website against this adjective. Ask yourself whether the content aligns with the adjective. Now pour over your design and assess it by the same measure. We’re looking for matching sensibilities. Does your content and design align with how you want users to feel about the website?

In Where the Wild Things Are, the narrative tone is the anchor in Max’s hectic journey. Consistent, calm and matter of fact, even when Max is off dancing with the wild things, the voice elicits the reader’s trust as it sees the protagonist back to safety.

Readers settle into this consistency the way Max settles into his boat for “in and out of weeks / and almost over a year / to where the wild things are,� and again “back over a year / and in and out of weeks / and through a day.� It steadies the commotion in Max’s imagination.

Here, readers recognize the tension between the consistent content and the disruptive visuals as the mark of a superbly imaginative journey, where anything can happen, but where eventually everyone must return home.

The narrative commits to this tension until the end, when Max gets back to his room, where dinner is waiting for him, “and it was still hot.�

As a children’s storybook, Where the Wild Things Are doesn’t employ multiple forms of narrative expression. But it is an effective example of the co-dependence of playful and experimental text and visuals, in which the narrative voice incites chaos and calms the senses at the same time.

One last example of a committed narrative voice:

Forefathers

Recalling Gold Rush-era drama and Victorian carnival sights with its effective design elements, Forefathers maintains an adventurous tone, employing text that is consistent, descriptively appropriate and authentic.

Be Mindful Of The User Experience

As Elizabeth McGuane and Randall Snare state in “Making Up Stories: Perception, Language and the Web,� as Web users scan pages, they are “filling in the gaps-making inferences, whether they’re based on past experience… or elaborate associations drawn from our imaginations.�

Trust the user to connect the graphics and text, and expect them to want to. Cloninger says that “the more power a user has to control the narrative himself, the more a visitor will ‘own’ that narrative.�

Keep the descriptions visual. The acts of “mischief� in Where the Wild Things Are are graphic. The connection is made when both elements are harmonized into one idea. The user will be willing to read the text and view the corresponding image if both elements are compelling.

Looking at Jonathan Patterson’s effective online portfolio, we can see he has maintained a fluidity of content and design by basing the user’s experience on the motif of “fresh meat�:

Jonathan Patterson

Patterson’s “About� page looks like a steakhouse menu. The text on the first page hints at a description of a meal, while suggesting the page’s function. The website can be flipped through like a menu, giving the user choice and control. The text is simple and linear, mirroring the sequence of appetizer, main course and dessert in a restaurant menu. Fluid text and design help Patterson to create a particular experience with his portfolio.

Maurice Sendak employs similar tactics in Where the Wild Things Are, encouraging readers to expand their gaze to match Max’s ever-growing visual landscape. As Max moves out of his room and onto the sea, the content on the right-hand pages (otherwise bordered in thick white space) creeps over gradually, thrusting more colors onto the facing page. At one point, a sea monster appears on the left-hand page, which was otherwise reserved for text and white space.

Here is the user experience at its most polished. The change comes quietly, invisibly, but the reader is aware that something is different. The protagonist’s growth has been connected with the reader’s experience of the narrative through the placement and cohesion of text and image.

Another polished example of fluidity in content and design can be found in an actual restaurant’s website layout:

Denny's Home

Yes, Denny’s. Look familiar? Replicating the experience of perusing a Denny’s menu, this layout shows how, in Patrick Lynch’s words, “visual design and user research can work together to create better user experiences on the Web: experiences that balance the practicalities of navigation with aesthetic interfaces that delight the eye and the brain.�

Denny's Menu

The user controls the narrative here, with fluid navigation options that maintain the menu-like aspect of the layout, and a pleasing visual presentation that, as Lynch says, “enhances usability.� Filling in the gaps between glancing over a Denny’s menu and browsing the website, users feel encouraged to control their experience.

Conclusion

Fluidity of content and design requires that you trust users to make connections. By making the tone consistent, backing up your claims, tightening the text and being sensitive to the user’s experience, you can be assured that users will draw the conclusions you want them to draw. Designers of promotional Web projects can learn these lessons in part from storybooks such as Where the Wild Things Are, which demonstrates the essential elements of user control and delight. Trust your inner child; it won’t steer you wrong.

(al)


© Sarah Bauer for Smashing Magazine, 2011.


Free Icon Set For Web Designers: Aroma (250+ PNG Icons)





 



 


Today we are delighted to release another freebie for our design community. There are many free icon sets out there, and there are quite many commercial ones as well. Yet a good, consistently designed icon set is always a welcome addition to any designer’s toolbox. Oliver Twardowski had released the Ultimate Free Web Designer’s Icon Set (750 icons, including PSD sources) in the past, and this time he has prepared a fresh, new icon set which contains over 250 original high quality PNGs. Please notice that some icons may be similar to the ones released in the previous set.

Screenshot

Download the Collection for Free!

The elements contained in this collection are free for personal and commercial use. Please link to this article if you want to spread the word or give it a tweet or share it on Facebook! You may modify the file as you wish but please do not redistribute them elsewhere without written permission from Smashing Magazine and Oliver Twardowski.

Screenshot

Screenshot

Screenshot

Screenshot

Behind the Design

As always, here are some insights from the designer:

“This set was started out in January 2011, so the whole design process took me nearly a year to finish. Including all the tiny, little, shy transparent PNGs and keys, the set is build out of 145.728 pixels. All icons were made with love in Cologne, Germany.

If you think that some icons are missing in this set, feel free to share your thoughts and ideas in the comments section below, contact me at aroma[at]addictedtocoffee[dot]de or find me via twitter at @mywayhome. Oh and did I mention: I’m always available for exciting freelance projects :)

Stay tuned! You never know  —  there might be a second part of the set coming out quite soon!”

Thank you, Oliver Twardowski. We appreciate your work and your good intentions!

(il) (vf)


© Smashing Editorial for Smashing Magazine, 2011.


  •   
  • Copyright © 1996-2010 BlogmyQuery - BMQ. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress