Archive for November, 2011

Designer Spotlight: Interview With Web and Graphic Designer Veerle Pieters


  

One of the things that we hear a lot in the design/development field tends towards keeping that passion alive which first drove us to this arena. For when we keep that flame burning, our work will always remain vibrant and successful. This idea is exemplified in our interviewee here, Veerle Pieters (one of the fascinating minds behind Duoh!), whose love for design in all its various forms shines through.

We’ll allow Veerle to introduce herself, informally in her own words, but we would like to take a moment and describe her in our words before we get to that. If you are not familiar with Veerle, her blog, or her work, then you are in for a real treat. Her work is as whimsical as it is precise, and packing as much personality as the lady herself. Her award winning work is a vibrant expression of her glowing inner child with the crisp, clean professional edge she has honed through years of imaginative exploration of graphic and web design.

Beginning as an illustrator in print design, Veerle grew her talents along with the world wide web giving her a much fuller perspective on the field of design overall. Her boundless talents are an inspiration to so many, and today we are lucky to be able to feature her and share some of her insights with our readers. Without any further ado, on with the interview…

The Interview & Showcase

Thanks again for agreeing and taking the time to answer these questions. So tell us a bit about yourself. Who exactly is Veerle Pieters? How would you describe yourself?

I always find talking about yourself extremely hard but here we go… I’m a graphic/web designer hailing from a small but beautiful European country called Belgium. I am a color lover that likes to listen to deep soulful music while designing. When I’m not at work I like to ride my bicycle to clear my head and snap pictures along the way to share on Instagram just to show how much beauty there is around us if you just open your eyes to see it.

Who are some of your biggest influences in web design?

Right now not really someone particular but many years ago when I started with web standards I was influenced by Jeffery Zeldman and Douglas Bowman and Dave Shea’s Zen Garden. I try to do my own thing and not be influenced by trends that overdo a certain design element. Personally I will use something that everybody claims you shouldn’t because I like to believe it’s all in the way how you apply it. I am of course also influenced by waves of techniques that popup in our industry like ‘responsive web design’ for example.

You’ve worked in both print and web design, which do you prefer and which offers the most freedom?

Print is still my first love because a web site can never replace that tactile feeling of having something in your hand you’ve created. Web design offers the most freedom, can be controlled easier and has a higher tolerance for error. Mistakes are deadly in print, especially when you are creating something that has a super high print volume.

What are some of your favorite projects you’ve worked on?

One of my favorite projects and most challenging ongoing project is without a doubt Fab.com. Another one is jolena.be where I really got the chance to explore creative boundaries. I wrote a little about the process of that project on my blog.

What advice would you give to other web designers?

I think the most important thing is to stay passionate about what you do and don’t loose that drive to constantly learn new things because we are part of a constantly changing environment. Learning and experimenting is a very important aspect of what de do. If you think you learned enough already I’m afraid that web design isn’t the right path for you. Also, believe in yourself and stay true to yourself and don’t be afraid to fail. Sounds cliché but that is what makes us what we are.

Can you give us a summary of your process?

Depending on how I feel and the amount of ideas that present I usually start by using my own Inspiration Stream as a starting place to look for that spark. Long time ago I browsed around CSS galleries but I’ve learned that they block my inspiration instead of helping. The most successful way is to look at things that aren’t related to web design at all such as my stream. When I got that inspiring spark I mostly start the process by doing some sketches in one of my little notebooks. Not always though, as I sometimes begin directly in Photoshop too. The more complicated projects have a wireframe stage that we go through first. Once those are approved by the client, the design work in Photoshop starts. I’m not part of the ‘design in a browser movement’ as I feel that approach blocks my creativity. About 90% of the projects, start with the inner pages first because these are usually the most difficult ones to work on. If the client approves the design we start the technical part by writing the CSS/HTML.

What are some of your thoughts on the importance of web standards?

Web standards are important but they are just guidelines, they aren’t a relegion if you understand what I mean. It’s a set of guidelines and best practices to help you but not a rule of law. It’s ok to deviate or improvise if you need to, and if there is no other way of doing it semantically. If you start mailing other people by pointing out validation errors you aren’t getting it. Projects can be complex and zero validation errors is sometimes impossible. The important part is that you try and that you think about structure, accessibility etc…

How do you convey the importance of web standards to your clients?

I don’t convey it all. I just do it. Clients shouldn’t have to worry about this or decide on, it’s up to us to use what is best for the client’s interest and web standards does just that.

What made you choose expression engine for your blog over other options?

I opted for ExpressionEngine because at that time it was the only system that would let me create a web site my way instead of the other way around that the system dictates how you should use it. I wanted something that I could use my templates, just the way I coded them, plus I wanted a system that didn’t inject extra code in my templates. Another important reason was that it was powerful enough to create a site that covered all my needs without having to resort to learning PHP because I needed to extend it. I had no interest in learning another program language as a designer.

What drew you away from print design to web design?

Because I was intrigued by this new thing called web design. I saw an opportunity that it could become something very important and that it would provide a source of income.

Web design changes so quickly, how do you keep up?

By reading books and following tutorials.

What are some of the biggest challenges that you see facing the web design industry today?

The biggest challenge imho is keeping up with our fast changing industry. Not an easy task to accomplish with a full workload all the time and a blog that needs attention too. One does need a lot of time filtering out what comes online to finally get to what will become a standard way of doing things.

What can we expect to see from you in the future?

There is some exciting stuff in the pipeline for Fab.com and I’m also working on a few projects that involve a lot of illustration work.

(rb)


Create a Business Icon from Scratch an Adobe Illustrator Tutorial


  

Business icons are one of the most poplar vector illustrations. As with all vectors in general, business icons are scalable which makes them perfect for use in web design. The best way to create an icon is to use one of the vector based programs, such as Adobe Illustrator, Corel Draw, etc. We are going to create an interesting business icon that consists of two arrows and a globe in this Adobe Illustrator tutorial. The techniques we are going to describe is applicable for creation other kinds of illustrations as well.

So, let’s get down to business.

This is what we will be creating.

Creating the Globe

Before we create the globe we need to prepare a grid of parallels and meridians. It means we have to prepare the symbol that we’ll apply to the globe. The Blend Tool will help us do that.

Grab the Line Tool (/) from the Tool Panel and create a vertical line. Now, select Add Anchor Point Tool (+) and add an anchor point exactly in the middle of the line.

Select the Direct Selection Tool (A) from the Tool Panel, grab that anchor point and drag it to the left (don’t forget to hold the Shift key on the keyboard for straight dragging).

This way we have created a sharp corner. We need to smooth it out. Grab the Convert Anchor Point Tool (Shift + C) from the Tool Panel, click on the anchor point and to drag it downwards (Shift for straight dragging).

Select the path and under Object select Transform > Reflect. Set the Axis to Vertical and hit the Copy button. It will create a mirror image of our path. Move the new path to the right (Shift for straight dragging).

Select both paths and under Object select Blend > Make. It will create more paths in the middle. To specify the exact number of the paths open Blend Options (Object > Blend > Blend Options). We’ll set the value for the Specified Steps to 17.

Grab the Line Tool (/) from the Tool Panel and create a horizontal line (Shift for straight dragging), as shown on the picture below.

Duplicate (Ctrl / Cmd + C, Ctrl / Cmd + F) the line and place it as pictured.

Select both horizontal lines and under the Object select Blend > Make. Set the value for Specified Steps to 9.

Select all the elements we’ve created so far and Group them (Ctrl / Cmd + G). Grab the group of elements and drag it to the Symbol Panel. Symbol Options window will pop up. Set the name to Grid, make sure to set the Type to Graphic and hit the OK button.

Now we have created a symbol which we’ll use to apply to our globe.

Creating the Globe

First of all, we have to create a circle. Grab the Ellipse Tool (L) from the Tool Panel and create a circle (don’t forget to hold the Shift key on the keyboard for the proper circle).

With the Direct Selection Tool (A) select the anchor on the left side and hit the Delete key on the keyboard to remove it. You should end up with something like this.

Under Effect select 3D > Revolve.

Under the 3D Revolve Options box make sure to set the Surface to Diffuse Shading and then hit the Map Art button. This is the where we are going to apply the symbol we created to our sphere.

In the Symbol drop down Menu select the symbol of the grid we have already made. Make sure to hit Scale to Fit button. It will apply the grid symbol properly.

You should end up with something like this.

Now we need to apply some nice color gradients. To be able to do that, first we have to turn our object into editable shapes. Under Object select Expand Appearance. Then we need to Ungroup (Shift + Ctrl/ Cmd + G) the object. Be ready to repeat that action a few times, until you “separate” the sphere from the grid. When you achieve that select the sphere (you’ll notice that it contains many concentric circles) and under the Pathfinder Panel hit the Unite button. This will turn the circles into a single one.

Set the Fill color for the grid to #61D4E0.

We are going to apply a nice blue radial gradient to the circle. It will turn our circle into a nice blue sphere.

There is one more thing we should add to the globe. Select the Rectangle Tool (M) from the Tool Panel and create the ellipse. Set its Fill color to white (#FFFFFF) and place it as it shown on the picture below.

Set the Opacity of the new ellipse to 26%.

Our globe is ready for some nice arrows. Before we create them don’t forget to Group (Ctrl / Cmd + G) all the elements of the globe together.

Creating the Arrows

To create nice 3D arrows we will be using 3D effect Revolve. It will help us to fold the arrow around the globe. So, lets get started. First we will create the shape of the arrow.

Grab the Rectangle Tool (M) and create a rectangle, as it’s shown on the picture below.

Now, grab the Star Tool from the Tool Panel and click on the Artboard. The Star Options window will pop up. Set the value for Points to 3 and hit the OK button.

It will create a triangle. Rotate it and place it as it show on the picture below. Align the shapes by using Vertical Align Center under the Align Panel.

When you are satisfied with the result under the Pathfinder Panel hit the Unite button. It will turn both shapes into the arrow shape.

Drag the arrow to the Symbol Panel and name it Arrow. Set the Type to Graphic. This way we are creating the symbol of the arrow which we’ll be using later.

Now, grab the Rectangle Tool (M) from the Tool Panel and create a rectangle, as pictured.

Under the Effects select 3D > Revolve. Check the Preview box in order to be able to see what are we doing. Under the Revolve Options box click on the Map Art button.

You will notice that the cylinder contains three sides. Upper ellipse, lower ellipse and the lateral side of the cylinder. Switch between sides, and when you select the lateral side of cylinder select the arrow in the drop down menu for Symbol. Also, make sure to check Invisible Geometry. It will remove the cylinder shape and only the arrow will be visible.

Feel free to play with the size and the rotation of the arrow, until you reach the right angle and position.

When you reach a desirable result hit the OK button. We can also change the rotation of the invisible cylinder in order to find the best position for our arrow by rotating the cube in the 3D Revolve Options box.

Now we have to turn our arrow into an editable shape. Select the shape with the arrow and under Object hit Expand Appearance. You should end up with something like this.

Lets Ungroup (Shift + Ctrl / Cmd + G) the new shape (we’ll have to do it more than once) and remove everything besides the arrow. This is what we should have by now (blue color is changed to be able to see the result clearly).

Take a good look at the arrow. See if there are any unnecessary anchor points and remove them.

Now we have to turn the arrow into a 3D shape. Select both parts of the arrow and duplicate them (Ctrl / Cmd + C, Ctrl / Cmd + F). Using the arrow keys on the keyboard nudge the copies a few pixels to the right and then downwards. You should end up with something like this.

We have to connect some shapes now. Grab the Add Anchor Point Tool (+) from the Tool Panel and add few anchor points.

With the Direct Selection Tool (A) grab the new anchor point and move it to the lower corner of the green shape.

Repeat this step for the other corners of the arrow as well.

To be able to create a glossy arrow with lots of reflected parts, we’ll have to divide some parts of the arrow. Select the Pen Tool (P) from the Tool Panel and create the path as it’s shown in the picture. We will use the path to divide the red part of the arrow. Just select them both (red shape and the green path) and under the Pathfinder Panel hit the Divide button. It will split the red shape exactly in half. Don’t forget to Ungroup it (Shift + Ctrl / Cmd + G).

And, now our arrow is ready to get some nice colors.

Applying the Color Gradients

In this part of the tutorial we will try to achieve a nice glossy look for the arrow.

To start we will apply some nice linear gradients.

Use a radial gradient for lateral side.

We can also divide the inner part of the arrow. Just create another path using the Pen Tool (P) and divide the inner side of the arrow. Apply a nice radial gradient to both sides.

We can also make some additional shapes that will help us to create the glossy look of the arrow. Select the right upper side of the arrow and under Object select Path > Offset Path. Set the value for Offset to -3 and hit the OK button.

With the Direct Selection Tool (A) move the upper side of the new shape. Just select the upper anchor points and move them upwards, as shown below.

Apply a nice linear gradient to the new shape.

We can do the same thing with the left side of the arrow. You should end up with something like this.

In order to create more light reflections we will divide some other parts of the arrow as well. Grab the Line Tool (/) from the Tool Panel and create a few random lines.

Use each of the lines to divide the surface underneath the line. Just select the line and the shape you want to divide and under the Pathfinder Panel hit the Divide button.

Apply a green radial gradient to the new shape, just make sure to create a sharp transition, just as it’s shown in the pictures below.

Repeat this step for the other shapes as well. It will create nice light reflections.

Some nice edge highlights will give our illustration a real glossy look.

The Final Touch

Now we will combine our globe with the arrows. To be able to set the two arrows in the right place we will have to learn to draw a Clipping Mask. A Clipping Mask is actually a random shape without the Fill and Stroke colors which allows us to hide some parts of the illustration.

Let’s get down to business.

Place the arrow on the top of the globe (as pictured). Duplicate (Ctrl / Cmd + C, Ctrl / Cmd + F) the arrow and send the copy behind the globe (Shift + Ctrl / Cmd + [). You should end up with something like this.

Grab the Pen Tool (P) from the Tool Panel and draw a shape similar to this.

When you are drawing the shape for the Clipping Mask keep in mind what parts of the arrows needs to be visible (everything inside the path will remain visible). Also make sure to follow the shape of the globe in order to avoid overlapping the globe and the part of the arrow that needs to be behind it.

When you are satisfied with the shape of the Clipping Mask remove the Stroke color, select the globe and the arrow and under the right click select Make Clipping Mask.

This action will hide all parts of the arrow outside the Clipping Mask. This way we have created the illusion that the arrow is "sitting" on the globe.

Duplicate (Ctrl / Cmd + C, Ctrl / Cmd + F) the green arrow behind the globe, Bring it to the Front (Shift + Ctrl / Cmd + ]) and change the color to red. Using the Reflection feature under Object > Transform > Reflect flip the arrow upside down by using reflection on a Horizontal and Vertical axis. You should end up with something like this.

Repeat the steps for creating the Clipping Mask and you should get something like this.

Feel free to create a few more shadows and some sparks…

…and we are done!

The Conclusion

Glad that you went through the entire tutorial. It will help you to create a really interesting web icon that can be used for different kinds of purposes (business, environment, communication, etc). Using this technique you can actually do other kinds of illustrations as well.

Just feel free to be creative and to explore the other possibilities. Hope you like this tutorial. Thank you for following along.

(rb)


Create a Business Icon from Scratch an Adobe Illustrator Tutorial


  

Business icons are one of the most poplar vector illustrations. As with all vectors in general, business icons are scalable which makes them perfect for use in web design. The best way to create an icon is to use one of the vector based programs, such as Adobe Illustrator, Corel Draw, etc. We are going to create an interesting business icon that consists of two arrows and a globe in this Adobe Illustrator tutorial. The techniques we are going to describe is applicable for creation other kinds of illustrations as well.

So, let’s get down to business.

This is what we will be creating.

Creating the Globe

Before we create the globe we need to prepare a grid of parallels and meridians. It means we have to prepare the symbol that we’ll apply to the globe. The Blend Tool will help us do that.

Grab the Line Tool (/) from the Tool Panel and create a vertical line. Now, select Add Anchor Point Tool (+) and add an anchor point exactly in the middle of the line.

Select the Direct Selection Tool (A) from the Tool Panel, grab that anchor point and drag it to the left (don’t forget to hold the Shift key on the keyboard for straight dragging).

This way we have created a sharp corner. We need to smooth it out. Grab the Convert Anchor Point Tool (Shift + C) from the Tool Panel, click on the anchor point and to drag it downwards (Shift for straight dragging).

Select the path and under Object select Transform > Reflect. Set the Axis to Vertical and hit the Copy button. It will create a mirror image of our path. Move the new path to the right (Shift for straight dragging).

Select both paths and under Object select Blend > Make. It will create more paths in the middle. To specify the exact number of the paths open Blend Options (Object > Blend > Blend Options). We’ll set the value for the Specified Steps to 17.

Grab the Line Tool (/) from the Tool Panel and create a horizontal line (Shift for straight dragging), as shown on the picture below.

Duplicate (Ctrl / Cmd + C, Ctrl / Cmd + F) the line and place it as pictured.

Select both horizontal lines and under the Object select Blend > Make. Set the value for Specified Steps to 9.

Select all the elements we’ve created so far and Group them (Ctrl / Cmd + G). Grab the group of elements and drag it to the Symbol Panel. Symbol Options window will pop up. Set the name to Grid, make sure to set the Type to Graphic and hit the OK button.

Now we have created a symbol which we’ll use to apply to our globe.

Creating the Globe

First of all, we have to create a circle. Grab the Ellipse Tool (L) from the Tool Panel and create a circle (don’t forget to hold the Shift key on the keyboard for the proper circle).

With the Direct Selection Tool (A) select the anchor on the left side and hit the Delete key on the keyboard to remove it. You should end up with something like this.

Under Effect select 3D > Revolve.

Under the 3D Revolve Options box make sure to set the Surface to Diffuse Shading and then hit the Map Art button. This is the where we are going to apply the symbol we created to our sphere.

In the Symbol drop down Menu select the symbol of the grid we have already made. Make sure to hit Scale to Fit button. It will apply the grid symbol properly.

You should end up with something like this.

Now we need to apply some nice color gradients. To be able to do that, first we have to turn our object into editable shapes. Under Object select Expand Appearance. Then we need to Ungroup (Shift + Ctrl/ Cmd + G) the object. Be ready to repeat that action a few times, until you “separate” the sphere from the grid. When you achieve that select the sphere (you’ll notice that it contains many concentric circles) and under the Pathfinder Panel hit the Unite button. This will turn the circles into a single one.

Set the Fill color for the grid to #61D4E0.

We are going to apply a nice blue radial gradient to the circle. It will turn our circle into a nice blue sphere.

There is one more thing we should add to the globe. Select the Rectangle Tool (M) from the Tool Panel and create the ellipse. Set its Fill color to white (#FFFFFF) and place it as it shown on the picture below.

Set the Opacity of the new ellipse to 26%.

Our globe is ready for some nice arrows. Before we create them don’t forget to Group (Ctrl / Cmd + G) all the elements of the globe together.

Creating the Arrows

To create nice 3D arrows we will be using 3D effect Revolve. It will help us to fold the arrow around the globe. So, lets get started. First we will create the shape of the arrow.

Grab the Rectangle Tool (M) and create a rectangle, as it’s shown on the picture below.

Now, grab the Star Tool from the Tool Panel and click on the Artboard. The Star Options window will pop up. Set the value for Points to 3 and hit the OK button.

It will create a triangle. Rotate it and place it as it show on the picture below. Align the shapes by using Vertical Align Center under the Align Panel.

When you are satisfied with the result under the Pathfinder Panel hit the Unite button. It will turn both shapes into the arrow shape.

Drag the arrow to the Symbol Panel and name it Arrow. Set the Type to Graphic. This way we are creating the symbol of the arrow which we’ll be using later.

Now, grab the Rectangle Tool (M) from the Tool Panel and create a rectangle, as pictured.

Under the Effects select 3D > Revolve. Check the Preview box in order to be able to see what are we doing. Under the Revolve Options box click on the Map Art button.

You will notice that the cylinder contains three sides. Upper ellipse, lower ellipse and the lateral side of the cylinder. Switch between sides, and when you select the lateral side of cylinder select the arrow in the drop down menu for Symbol. Also, make sure to check Invisible Geometry. It will remove the cylinder shape and only the arrow will be visible.

Feel free to play with the size and the rotation of the arrow, until you reach the right angle and position.

When you reach a desirable result hit the OK button. We can also change the rotation of the invisible cylinder in order to find the best position for our arrow by rotating the cube in the 3D Revolve Options box.

Now we have to turn our arrow into an editable shape. Select the shape with the arrow and under Object hit Expand Appearance. You should end up with something like this.

Lets Ungroup (Shift + Ctrl / Cmd + G) the new shape (we’ll have to do it more than once) and remove everything besides the arrow. This is what we should have by now (blue color is changed to be able to see the result clearly).

Take a good look at the arrow. See if there are any unnecessary anchor points and remove them.

Now we have to turn the arrow into a 3D shape. Select both parts of the arrow and duplicate them (Ctrl / Cmd + C, Ctrl / Cmd + F). Using the arrow keys on the keyboard nudge the copies a few pixels to the right and then downwards. You should end up with something like this.

We have to connect some shapes now. Grab the Add Anchor Point Tool (+) from the Tool Panel and add few anchor points.

With the Direct Selection Tool (A) grab the new anchor point and move it to the lower corner of the green shape.

Repeat this step for the other corners of the arrow as well.

To be able to create a glossy arrow with lots of reflected parts, we’ll have to divide some parts of the arrow. Select the Pen Tool (P) from the Tool Panel and create the path as it’s shown in the picture. We will use the path to divide the red part of the arrow. Just select them both (red shape and the green path) and under the Pathfinder Panel hit the Divide button. It will split the red shape exactly in half. Don’t forget to Ungroup it (Shift + Ctrl / Cmd + G).

And, now our arrow is ready to get some nice colors.

Applying the Color Gradients

In this part of the tutorial we will try to achieve a nice glossy look for the arrow.

To start we will apply some nice linear gradients.

Use a radial gradient for lateral side.

We can also divide the inner part of the arrow. Just create another path using the Pen Tool (P) and divide the inner side of the arrow. Apply a nice radial gradient to both sides.

We can also make some additional shapes that will help us to create the glossy look of the arrow. Select the right upper side of the arrow and under Object select Path > Offset Path. Set the value for Offset to -3 and hit the OK button.

With the Direct Selection Tool (A) move the upper side of the new shape. Just select the upper anchor points and move them upwards, as shown below.

Apply a nice linear gradient to the new shape.

We can do the same thing with the left side of the arrow. You should end up with something like this.

In order to create more light reflections we will divide some other parts of the arrow as well. Grab the Line Tool (/) from the Tool Panel and create a few random lines.

Use each of the lines to divide the surface underneath the line. Just select the line and the shape you want to divide and under the Pathfinder Panel hit the Divide button.

Apply a green radial gradient to the new shape, just make sure to create a sharp transition, just as it’s shown in the pictures below.

Repeat this step for the other shapes as well. It will create nice light reflections.

Some nice edge highlights will give our illustration a real glossy look.

The Final Touch

Now we will combine our globe with the arrows. To be able to set the two arrows in the right place we will have to learn to draw a Clipping Mask. A Clipping Mask is actually a random shape without the Fill and Stroke colors which allows us to hide some parts of the illustration.

Let’s get down to business.

Place the arrow on the top of the globe (as pictured). Duplicate (Ctrl / Cmd + C, Ctrl / Cmd + F) the arrow and send the copy behind the globe (Shift + Ctrl / Cmd + [). You should end up with something like this.

Grab the Pen Tool (P) from the Tool Panel and draw a shape similar to this.

When you are drawing the shape for the Clipping Mask keep in mind what parts of the arrows needs to be visible (everything inside the path will remain visible). Also make sure to follow the shape of the globe in order to avoid overlapping the globe and the part of the arrow that needs to be behind it.

When you are satisfied with the shape of the Clipping Mask remove the Stroke color, select the globe and the arrow and under the right click select Make Clipping Mask.

This action will hide all parts of the arrow outside the Clipping Mask. This way we have created the illusion that the arrow is "sitting" on the globe.

Duplicate (Ctrl / Cmd + C, Ctrl / Cmd + F) the green arrow behind the globe, Bring it to the Front (Shift + Ctrl / Cmd + ]) and change the color to red. Using the Reflection feature under Object > Transform > Reflect flip the arrow upside down by using reflection on a Horizontal and Vertical axis. You should end up with something like this.

Repeat the steps for creating the Clipping Mask and you should get something like this.

Feel free to create a few more shadows and some sparks…

…and we are done!

The Conclusion

Glad that you went through the entire tutorial. It will help you to create a really interesting web icon that can be used for different kinds of purposes (business, environment, communication, etc). Using this technique you can actually do other kinds of illustrations as well.

Just feel free to be creative and to explore the other possibilities. Hope you like this tutorial. Thank you for following along.

(rb)


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.


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