larryaronson.com

Creating a custom “Popular Posts” widget

I have a blogging client who has a love-hate relationship with computing. This client publishes daily and has become quite adept at the mechanics of doing so, successfully building traffic and a solid following. But when it comes to handling the blog’s administrative tasks, my client balks, refusing to look at any of the admin level menus. “I don’t like being a person who knows just enough to be dangerous,” my client has said.

The latest request from this client was to list the blog’s most popular posts in the sidedbar. It’s a WordPress site and there are many plugins available that will provide a widget for this task. Most are based on comment count as this is the metric that WordPress stores with each post record in its database. Some of the more sophisticated plugins make API calls to other services, such as Twitter and Google, to gather ranking data.

But nothing worked quite right for this client who had become a proficient Google Analytics user as well as a ardent Twitter user. I couldn’t find a popular posts plugin that would reliably match my client’s own subjective sense of popularity. I finally sent an email saying: “You want your readers to see your best stuff, in that respect, the numbers can provide guidance but your own judgement is the best metric.” I promised to figure something out that would allow the selection and ranking of posts although I didn’t have a clue how.

One of the joys of computer programming comes from those moments when you recognize that the particular little problem you’re working on is just a special case of a larger, more interesting and easier to solve problem. In this case, the larger problem was how to enable a WordPress author to publish formatted content to a sidebar widget. If I could solve that problem then my client could simply edit a page containing an ordered list of titles linked to the most popular posts. These could easily be copied from other pages in the WordPress dashboard. The client wouldn’t  need any admin level privileges. All I had to do was setup a text widget with code that pulled in the content of a designated page — A sidebar page.

How to build a WordPress sidebar page widget

Rather than write a dedicated sidebar widget, which is kind of complicated even though the WordPress codex has several examples to copy and paste from, I decided to write a WordPress shortcode which could be used in a sidebar text widget. This shortcode could also be used in other posts or pages on the site — going again for the more general and easier solution.

To start with, I created a new static page with the title, “Popular Posts”. Before you do this and publish the new page, check to see if it will automattically appear in your navigation menus. If you’re using the Menu Manager (included in WordPress 3.0+,) you’re probably okay since there’s a setting for this that’s off by default. If your theme does not use the Menu Manager, you might want to make the new page a child of some other page to exclude it from your navigation.

Next, we have to write a function that will output the contents of a page. This is easy. WordPress provides a built-in function just for that purpose called, get_page( ). We are going to use a variant of that function, get_page_by_title( ), and pass the title of the page (instead of the ID) as a shortcode parameter. Here’s the code for the function:

function my_show_page( $atts, $content = null ) {
    extract(shortcode_atts(array( 'title'=>'' ), $atts));

    if ($title != '') {
        $page_data = get_page_by_title( $title );
        return $page_data->post_content;
    }
    else {
        return '';
    }
}

The first two lines are the standard setup for a shortcode. The parameter, $atts, will contain the shortcode’s parameters. In our case this is the page’s title which is then extracted by the second line of the code. If no title is passed, it’s given an empty string value. Setting the variable $content to null allows us to place the simple shortcode:

[showpage title="Popular Posts"]

wherever we want to display the content of the page “Popular Posts” .

The body of the function is a simple if statement that makes sure a title is provided, then goes and gets the content of that page and returns it. Note that the content is returned unfiltered. That is, it’s unaffected by any plugins (e.g: ShareThis) or other code that modifies content.

The function code goes into your theme’s function file,  functions.php. Make sure you backup this file before you make any changes!! The function code can go anywhere in the file (except, of course, inside of another function) provided that it’s inside a set of php tags.

The next step is to register the shortcode so that it’s available for use. This is just a short command that also goes in the theme’s function file:

add_shortcode('showpage', 'my_show_page');

It can go either before or after the function. I usually place it after the function along with comments to guide any future programmers who may work on my clients’ sites.

Next, we have to enable shortcodes in text widgets. This is not enabled by default in WordPress because of security concerns. Sidebar text widgets are places where people often embed code from outside sources. The concern is that such embeded code might contain a shortcode that could conflict with something else on your blog or otherwise do nasty stuff. This is usually not a problem for smaller, personal blogs, however, I’ll emphasize again the importance of backing up your theme’s functions file before making any changes. Here’s the command to enable shortcodes in text widgets:

add_filter('widget_text', 'do_shortcode');

Add the above to your functions file, save it and test the blog in a separate browser window to be sure it’s still working. Errors in a theme’s functions file will usually crash the public portion of a WordPress blog, but will leave the admin dashboard in working order.

Lastly, add a text widget with the shortcode to your sidebar. Here’s a screenshot from my client’s site illustrating this.

Text Widget with a shortcode

For your convenience, here’s the entire block of commented code that I added to my client’s function file:

/**
* Create a shortcode to display a page's content
*/
//
// [showpage title="page_title"]
//
function my_show_page( $atts, $content = null ) {
    extract(shortcode_atts(array( 'title'=>'' ), $atts));
    if ($title != '') {
        $page_data = get_page_by_title( $title );
        return $page_data->post_content;
    }
    else {
        return '';
    }
}
// register the shortcode
add_shortcode('showpage', 'my_show_page');
//
// Enable the use of shortcodes in text widgets.
add_filter('widget_text', 'do_shortcode');

Now that we see how easy it is to get formatted content into a sidebar widget, perhaps you have some ideas on what can be done with custom shortcodes in sidebar widgets. If so, please share them by leaving a comment below. Thanks.

15 HTML5 FAQs

Since the publication of HTML Manual of Style, I’ve attended a number of meetups and participated in a few forums to promote the book. While a lot of people are curious about HTML5, few really understand what it’s about and many have misconceptions.  So, I’ve collected 15 frequently asked questions about HTML5 along with my short answers in an effort to clear up some of the confusion. Click on a question to toggle open/close its answer.

  1. Is HTML5 is the new standard for creating Web pages?

    Not Quite. HTML5 is a draft proposal for a standard that will eventually be submitted to international standards organizations which may adopt HTML5 as a standard or may choose to adopt a competing proposal. Right now there’s no serious contender to HTML5 and all of the big players: Apple, Google, Mozilla, Microsoft and Adobe are behind it, so it is becoming the de-facto standard. However, it is still early in the process. The World Wide Web Consortium (W3C) expects to finalize the draft and start the process of final review and requests for comments in 2012. Final acceptance as a standard will happen several years after that.

  2. Is HTML5 a new technology?

    No. It’s an extension of existing HTML, adding new elements to the set recognized by HTML4 level browsers and removing some of the restrictions of xhtml.

  3. How does HTML5 affect my existing HTML4 website?

    It doesn’t. The HTML5 specifications require browser makers to support valid HTML4 web pages. You should update your HTML editing tools when new versions are available. If your web pages require a diet of strict xhtml, you should validate any third-party HTML5 code to one of the xhtml standards before embedding that code into your own pages.

  4. What is new about HTML5?

    Several things. The biggest change is that HTML5 documents are explicitly recognized as interactive applications. Every document element in HTML5 has a corresponding JavaScript API that describes how that element should behave in response to user actions and other events.

  5. Are there new HTML5 tags?

    Yes, there are new HTML5 elements that provide richer semantic descriptions of documents: section, article, header, hgroup, footer, aside and nav; new media elements: audio, video and canvas; new form input types: email, url, number range and search; and a bunch of new element attributes.

  6. Have any HTML elements changed their meaning or how they are used?

    Yes, but not many. The small element, which in HTML4 has no semantic value—it just means make the text smaller—is used in HTML5 to markup disclaimers, legal notices and the like—the small print. The anchor element, which creates hyperlinks, can now enclose any other elements excluding other links and buttons. In HTML4, the anchor was strictly an inline element.

  7. Are there things in HTML4 that are not in HTML5?

    Yes, but only a handful of elements and these are not really gone; they are just marked as obsolete. Browser makers can continue to support these elements in their new versions and most will. Among the elements marked as obsolete in HTML5 are: frame, frameset, big, center, font, strike, acronym, applet, isindex and dir.

  8. What exactly is HTML5 Video?

    Nothing, really. The term HTML5 video is used to differentiate the playing of a video directly by a browser encountering a web page’s video element, as opposed to being played by a third-party browser plugin via an object or embed element. There is nothing intrinsic about any video that makes it HTML5-ish as opposed to Flash-ish. The distinction is entirely a matter of how the a web page is coded to present the video.

  9. Is HTML5 video better than Flash video?

    Yes, but not in terms of video quality which is a function of how the video data is encoded. HTML5 video is better because the video element can interact with other elements on the page and can be styled using CSS. Also, HTML5 video should use less resources because it is built into the browser.

  10. Will HTML5 kill Adobe’s Flash?

    Nope, Flash will be around for a long time. As a media player, Flash accommodates digital rights management (DRM) which hasn’t been addressed in the HTML5 specs. As an applications platform, Flash has a large, installed base in corporate environments where there’s no compelling rationale for rewriting working applications in HTML5. For new applications, HTML5 has advantages over Flash: content is better exposed to search engines, there’s complete integration with other document elements, no plugins are required and HTML5 tools are free.

  11. Is HTML5 is a threat to Microsoft?

    No. Microsoft embraces HTML5. The IE9 beta has received high marks for its HTML5 support. Silverlight is not the only path to interactivity in Redmond.

  12. Is HTML5 ready for prime time?

    Some of it is and some of it isn’t. New HTML5 semantic elements have good support in all modern browsers, including IE if an HTML5 shim or the Modernizer JavaScript library is loaded into a web page. The audio, video and canvas elements are not supported in Internet Explorer yet, but these elements are designed to gracefully fail and fallback to other technologies, like Flash and Silverlight, in legacy browsers. Other technologies that are associated with HTML5 such as Mathematical Markup Language (MathML), Scalable Vector Graphics (SVG), Web Sockets, Web Storage and Geo-location have only limited support in the current crop of browsers.

  13. Where can I get an HTML5 browser?

    Opera, Chrome and Safari provide pretty solid support for HTML5 in their current versions including their browsers for iPhones, iPads and Droids. Firefox’s support for HTML5 is weak in its current version (3.6) but quite robust in the Firefox4 public beta.

  14. What about Internet Explorer?

    Internet Explorer is late to the HTML5 party. There’s no HTML5 support in IE8 or previous versions. However, adding a JavaScript library such as Google’s HTML5 shim or Modernizer enables IE 6, 7 & 8 to recognize the new semantic level elements so they can be styled with CSS. HTML5 support is good in the beta version of IE9 which is available for Windows Vista and Seven users. Unfortunately, the Windows 7 mobile browser is built largely on the IE7 code base.

  15. What is an HTML5 application?

    There are several new capabilities in HTML5 which directly address the need for creating interactive applications. Of course, HTML has had interactive capabilities since its early days with text-based input forms and HMTL5 expands these with new input types. New capabilities include page and session-based data storage in the user’s browser, Web sockets for inter-application communications, and a drawing environment,  the canvas element, for creating and manipulating image data.

I had the pleasure once again of working with Matt Hill of MacGroup. I had previously rebuilt the Profoto-USA blog for them and this new project was a blog for another of their clients in the world of photography: the Sekonic Company, a premier manufacturer of photographic light meters.

Sekonic Blog - front pageIt was a rather quick project thanks to the detailed Photoshop document provided as a spec for the front and single post pages. I started by creating a child theme from WordPress’s default Twentyten theme. The advantage of using a child theme is that all of your theme modifications are isolated in the child theme directory and are preserved when the theme is updated. Knowing that the way WordPress handles images in due for a revision in an upcoming version, I wanted to position Sekonic’s blog to take advantage of any new image handling features WordPress introduces via the default theme.

This was the first blog on which I implemented a Featured Post capability and I combined that with one of my favorite theme mods: the excerpt switch, to provide the post author with finer control of what appears on the blog’s front page. If a post has a featured image, then the medium-sized version of that image appears on the front page above the post’s body or excerpt. A featured image can be one of the images appearing in the post, an image from the site’s Media Library or an external image referenced by a URL.

Matt also gave me the freedom to use CSS3 on the blog to create the rounded corners and drop shadows in the design spec. To achieve these kinds of effects without using the CSS3 border-radius and box-shadow properties, a designer must create three overlapping division elements with different background images for the top, bottom and sides of a box. With CSS3, only a single element is needed and no background images have to be loaded. The disadvantage is that border-radius and box-shadow are recognized by the current versions of Firefox, Safari, Opera and Chrome but not by Internet Explorer. IE9, now in beta release, does support these properties so it’s only a matter of a few months time before IE users get the full design treatment.

Then, just for fun, I added CSS3 transitions to the navigation tabs. The idea behind CSS3 transitions is that when an element’s property changes (e.g: the background and text color of an navigation tab when the mouse hovers over it, ) the duration and other aspects of the transition can be controlled.  For the Sekonic Blog’s navigation tabs, I specified a 1.5 second duration from the base state (dark background, light-blue text) to the hover state (gray background, white text with drop-shadows) to visually reflect the blog’s tagline: “Control Light”.

I hope you enjoy the Sekonic blog. Building a website with such good writing and compelling images was a real pleasure for me.


Now Hear This!

His Master's VoiceWith all the talk about Flash versus HTML5 you might be forgiven for thinking that HTML5 is just about video. It’s not, of course. HTML5 is a major extension of HTML in many areas including media.

Today, I’d like to explore HTML5 audio, which is similar to HTML5 video in many respects, but fundamentally different in others. For starters, a video element is essentially just a TV set embedded in a webpage whereas audio can serve multiple purposes – four examples:

  • Sound effects. A button can make a sound when it’s clicked. How about a swoosh sound when a division is toggled open or closed?
  • Alerts and notifications. A little bell can sound when an AJAX request completes and updates a page section. Or, an audio “Uh Oh!” can play when you enter a malformed email address into a input field.
  • Background sounds. Some web pages can benefit from background music. But say you have a photo gallery of birds. Wouldn’t it be nice to be able to click one and hear it tweet?
  • Spoken content. Yes, we have podcasts, but we also need something simpler such as pronunciations of foreign words and phrases, or a click-to-have-this-post-read-to-you feature so you can go off and browse other webpages while I continue to read this one to you.

S i l e n c e.

Yo Dawg, I can’t hear your website!

This isn’t as dumb a statement as it first, um, sounds. Web developers have shied away from including sound in webpages because of several difficulties:

  • Confusion – There are codecs and there are file formats. A codec is a method of encoding audio data. A file format is a container for the codec and optional metadata, such as a song title. Some file formats can accommodate multiple codecs; other formats are codec specific. For simplicity, we can narrow this discussion to the most popular file formats/codecs for the Web. These are:
    • wav – An uncompressed format. A wav file with 30 seconds of silence is the same size (megabytes) as a file with 30 seconds of symphonic music.
    • mp3 – A popular format for music that uses a lossy compression format resulting in file sizes typically 1/10 the size of a wav file with the same audio content.
    • ogg – An open-source alternative to mp3 that also uses a lossy compression format.
  • Cross-browser incompatibility – Unlike images, where all major browsers support the three major file types—gif, jpg and png—all browsers do not support all audio formats. For instance: mp3 is a proprietary format and its decoding software cannot be included in GPL-licensed, open-source applications such as the Mozilla Foundation’s Firefox browser. Here’s a table showing which formats are supported by the current versions of the major web browsers:
    IE Firefox Safari Chrome Opera
    wav NO YES YES NO NO
    mp3 NO* NO YES YES YES
    ogg NO YES NO YES NO

    (* IE8 does not recognize the audio element at all. The IE9 beta works only with mp3 files. )

  • Plugin required – HTML4 Browsers do not support audio natively. A plugin is required and JavaScript must be enabled. While most browsers support audio with a distributed default plugin, web developers must still use the ugly and opaque object, embed and param elements to bring sounds to a webpage.
  • Insufficient processing power – For the first time visitor to a page, it can take several seconds for an older or overloaded browser to load the player code, download, decode and play a audio file. This pretty much nixes using sound for mouseover effects, even simple click sounds for navigation buttons.

YouTube made Web video workable. No such service existed to popularize the use of audio in webpages. On the contrary, Napster.com and iTunes focused attention on downloadable music applications. Wouldn’t it be great if there was an easy way to incorporate sounds on a webpage for other purposes. Good News! There is. All major browsers now support basic HTML5 audio with the notable exception of Internet Explorer.

The HTML5 Audio Solution

HTML5 audio consists of the audio element and a JavaScript API for playing the sound it represents. The element is a container (it has both opening and closing tags) and what’s inside is fallback content for legacy browsers and search-bots. It can be written simply as:

<audio src="url" autoplay loop>
        Aw, snap. Your browser doesn't support HTML5 audio!
</audio> 

The above would be perfect for playing background music on a webpage. it could be placed anywhere in the body of the document—heard but not seen. For creating a controllable audio player, the controls attribute can be added to the opening tag.

<audio src="url" controls>
        <a href="url">Download the audio file</a>
</audio> 

Which, depending on your browser will create a player like one of these:*

IE    Download the audio file
Firefox Firefox audio controls
Safari Safari audio controls
Chrome Chrome audio controls
Opera Opera Audio controls

(* Just pictures of the controls in different browsers. They don’t work here; neither does the link.)

Unfortunately, because of the differing support among browsers for the three file types, this approach won’t work in all browsers. That means having at least mp3 and ogg audio file versions and using browser detection to figure out which to load.

But wait. There’s an alternate form of the audio element that takes a different approach: try one format and, if it doesn’t work, try another. You still need at least two files but the syntax is much simpler.

<audio id="bgSound" loop>
        <source src="audio/bgSound.mp3" type="audio/mp3" />
        <source src="audio/bgSound.ogg" type="audio/ogg" />        
        <-- lnsert fallback Flash Player code here --">
</audio> 

The audio element must be in the body of the html document. I’ve given an id attribute to the above so it can be referred to by JavaScript statements. Place a script element right after the audio element to get its DOM object:

<script type="text/javascript">
  var bgSound = document.getElementById('bgSound');
</script>

Don’t put the JavaScript in the head of the document, the audio element must be defined before its DOM object can be referenced. The DOM object for the audio allows you to change its properties, start and stop the music. To play the audio as page background, add an onload attribute to the body tag:

<body onload="bgSound.play();">

As an alternative, use jQuery in the document head to call the play method at document ready time (when all the HTML is parsed but images may still be loading.)

<script type="text/javascript">
  $(document).ready( function () {$('#bgSound').play();} );
</script>

The jQuery $ function is similar to JavaScript’s getElementById( ) method. You’ll need the jQuery library for this to work. If it isn’t already loaded, placing the following script element in the document head will get it from Google.

<script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js">
</script>

To play a sound effect when the user’s mouse is over a link, remove the loop attribute from the audio tag and add preload, then use the onmouseover attribute in the link. You can get the DOM object and play it in one move:

<audio id="thanks" preload>
        <source src="audio/thanks.mp3" type="audio/mpeg" />
        <source src="audio/thanks.ogg" type="audio/ogg" />
</audio> 

<a href="javascript:void(0);" 
   onmouseover="document.getElementById('thanks').play();">A shout out</a>

Or, to assign a sound to a button like the one at the bottom of this post

<audio id="ella" preload>
        <source src="audio/swonderful.mp3" type="audio/mpeg" />
        <source src="audio/swonderful.ogg" type="audio/ogg" />  
</audio>

<button onclick="document.getElementById('ella').play()">
        I like it!
</button>

The JavaScript API for HTML5 Media elements contains many more properties and features including a track property which can be used to segment a file into separate sounds of different durations. One audio element could be used to (pre)load dozens of different sound effects for a website. Not all advanced API features will be supported by all browsers in the near future, but eventually, using sound on a website will become as natural and as easy to do as using images.

A shout out to my friends at WWWAC who helped test HTML5 Audio on the IE9 beta release.

What do you think of HTML Audio?   


HTML Manual of Style front coverThe HTML Manual of Style is a clear, concise reference for Hypertext Markup Language, including the exciting new features of HTML5, CSS3 and JavaScript.

It is intended as a guide for content creators and Web developers who wish to  create webpages pleasing to people and search robots.

The book contains dozens of examples of HTML techniques to add style to any website. Plus, an entire chapter is devoted to using HTML on blog posts, eBay selling pages, Google Docs, Wikipedia articles and in email marketing.

This edition, published by Addison-Wesley, is the fourth edition of HTML Manual of Style originally published by Ziff-Davis Press in 1994.

Links to HTML Manual of Style pages on the Web.


Oradell Animal Hospital website screenshotOradell Animal Hospital of Paramus, New Jersey is one of the largest and best animal and pet care centers in the world. But its website was old and the graphics designer who did their updates was closing her shop and leaving the country.

Their marketing director was looking for new ways to connect with their current clients and customer base but didn’t have to budget to do a full redesign of their web site. Recreating the current site’s structure and design in WordPress, adding social sharing and other functionality with plugins and widgets  looked like the solution but there would be challenges in the project.

  • There were over 300 html files on the existing site without much organization. A major overhaul of the web site had apparently been done 6 or 7 years ago but the earlier generation of files had not been deleted. Internal links and navigation menus were a mess.
  • A two column front page that pulled post lists from different categories needed to be built and it had to be editable by the client. Templates for other special page types would need to be created.
  • Oradell needed a way to manage their busy calendar of events which included everything from special lectures to pet bereavement group session at multiple locations.
  • A large amount of content had been collected over the years that needed curating and conversion including profiles and pictures of 100 doctors and staff. I would need to duplicate their doctor-popup windows.

Lisa Davis, Oradell’s director of marketing and I worked our way through the content sorting the pages into a navigable hierarchy. We played with the front page’s features and layout over the course of the project until it finally looked and felt right. I built a special template for the Services & Staff pages that included a dynamically generated menu of all of the hospital’s departments. Each department’s page is a child page of the Services & Staff page.

I installed the WordPress events manager. This is a powerful piece of programming. It’s highly configurable and easy to use but, otoh, required a lot of configuration for Oradell’s requirements.

The most fun was writing shortcodes – one to show posts from a specific category in the content of a page and another to insert a doctor or staff profile in a post or page. The first  shortcode:

[showposts category="featured" display="title"]

in the content of a page produces a listing of permalinked post titles in the “featured” category. The other choices for the display option are “excerpt” and “post”. These are used throughout the site.

The doctor shortcode was more complicated because doctor information needed to be displayed in different contexts with different requirements: in the body of a post, on the various departments pages and in the complete directory of personnel. For each doctor or staff member, the profile consisted of the person’s name, academic credentials, job title, image and bio. Since several of their doctors were interested in blogging, I decided to register all the doctors and staff as blog contributors and use the extra IM user fields to store the titles and credentials. For example, using this shortcode in a post:

[doctor name="John Dolittle" role="true" creds="true" hide="false"]

will cause Dr. Dolittle’s (not an real Oradell employee) complete profile to be inserted, including his credentials and job title following his name plus the bio with a left-aligned photograph. Setting the hide parameter to “true” will hide the bio and photo but with a jQuery toggle, Somewhat like this:

John Dolittle, DVM, MD – Chief of Staff

All in all, I liked working on the new Oradell website. It presented interesting challenges and the people I worked with were wonderful.

Reimagine America

Reimagine America - front pageA good friend recommended me for a “need a website developer” post on the The Marketing Executives Networking Group (MENG) list. The poster was Joyce Cordi, a management and business consultant based in San Jose, California. Joyce is passionate about politics and ran for Congress in 2008. An outspoken advocate for sense in government, she had started her Reimagine America blog on WordPress.com but wanted to move past the limitations of the free hosting service. She also wanted a customized front page that pulled in content from her about and bio pages along with selected posts on various topics.

Even though I gave her my standard disclaimer that I am an information architect, not a graphics designer, she gave me full reign on changing any design elements. “Just don’t make me look at a bunch of themes!” was her only requirement.

“That’s fine.” I replied. “you’re already using the MistyLook theme which I like so much that I’ve used it on my own site.” All that was needed design-wise was a change from MistyLook’s muted grays and greens to patriotic reds, whites and blues.

The big unknown in estimating the time and cost of this project was podcasting. The vast majority of Joyce’s posts consist of transcripts following an audio player control. Joyce complained about the difficulty she and her producer, Wayne, had in getting each podcast attached to a WordPress.com post. I hadn’t done much work with podcasts so I couldn’t tell if the problems stemmed from her methodology or from a problem with WordPress.com itself. The only way to find out was to copy one of her audio files and try to setup podcasting on my development site.  I started with PodPress, one of the more popular podcasting plugins. It worked like a charm.

Building a replacement WordPress site is not as straight forward as it might seem. A WordPress installation internalizes its URL. By that I mean the site’s full URL is stored in the database in several places and this complicates creating a new WordPress instance on any address other than the final production URL. There are two ways around this problem, both of which present difficulties.

  1. Build the site on a temporary URL and convert to the production URL at launch time.
  2. Modify the local DNS on a development machine in order to install the site on the production URL.

The first approach is easier up to the conversion point. The conversion requires dumping the database, running it through a filter to change the internal URLs and reloading. It’s kind of scary since it essentially means killing and resurrecting the site, then waiting a few nail-biting hours for the DNS change to propagate across the Internet before you know if the conversion was successful or not.

The second approach is safer but  has the downside that the new site cannot be seen by the client unless she also has a spare machine on which she can modify her local DNS. Even if that’s the case, modifying your local DNS is not trivial, especially on a Windows PC where, if you don’t do it right, you can screw up your entire Internet access.

Still, whenever possible, I use the second approach and send emails with screenshots when I need the client’s input. I did this with Reimagine America but, instead of email, Joyce and I communicated using Skype, taking advantage of its screen sharing and file transfers capabilities to work together on the design and layout.

For Reimagine America’s front page, I imported the showposts shortcode function I used on Oradell.com. This allowed Joyce to choose which topics (WordPress categories) to feature, how many posts to show in each topic and whether to show just the title or the title and excerpt.

Reimagine America Articles PageAs a bonus, I also copied the “Show All Articles” page that I developed for Profoto-USA extending it with the ability to sort by category as well as by date and title. I find having a page with the full index of all post titles an important addition to any blog. Click on the screen shot to the right to see the page in action. 



A lot of the noise around HTML5 has been about whether or not it will replace Flash as the primary means of delivering video content over the Web. While I believe that HTML5′s simple, native video element is superior to Flash’s plugin-based mess of object, embed and param elements, Flash isn’t going away anytime soon. The noise, however, drowns out information about other interesting HTML5 features, two of which, content editable-ness and local storage, I’ll explore in this article with a simple example. Google’s Chrome browser supports both of these features; other browsers support one or the other, or neither.

Local StorageLet’s say you have a page on your website and you would like to offer your readers the ability to jot down notes related to the content of that page in some kind of input field. Furthermore, since you expect visitors to revisit the page from time to time, you’d like to store their notes somewhere so that the input field can be loaded when they next load the page. Before HTML5, you would either use a server-side process, cookies or some combination of the two to make this happen. With HTML5, there’s a third choice: the localStorage window object.

First, let’s start with the input field. We could use a textarea element but in HTML5, any element can be turned into an input element by adding the contenteditable attribute:

<ul id="notepad" contenteditable="true">
  <li></li>
</ul>

In the  CSS for this list element, we want to set its size and position:

#notepad {
 height: 20%;
 width: 20%;
 display: none;
 position: fixed;
 top: 0.5in; right: 0.5in;
 overflow: auto;
 padding: 1em;
 border: thin solid;
 list-style-type: none;
 background-color: #fffff0; /* light yellow */
}

This will place the list element 1/2 inch down and in from the top-right corner of the browser’s window. The bordered box will take up 1/5 of the window’s width and height and scrolling will be enabled if there is more content then fits. The display property is set to “none” initially. The user will be able to make the notepad list visible by clicking a button with an onclick handler.

<button id="notepad_toggle"
        onclick="$('#notepad').toggle()">Notepad</button>

I’m using jQuery for the onclick handler because it makes it easy to target elements . If you copy this code, make sure you load jQuery somewhere in the document’s head.

HTML5 extends the window object with the localStorage property and two primary methods: setItem(name, value) and getItem(name) to set and retrieve name/value pairs of data items. Any number of such items can be stored with a webpage and each page’s storage object is independent of any other page’s. Unlike cookies, local storage items are never sent by the browser to the server and thus provides a efficient means of saving page state information even for megabyte data items.

For our example, we can store the contents of the notepad element each time it is changed. We will do this with the blur method, detecting when the user leaves the notepad to do something else. Here’s some jQuery that does that nicely:

$('#notepad').blur(function () {
  localStorage.setItem('notepad', this.innerHTML);
});

How nice is that? The storage doesn’t have to be initialized; it’s just there waiting for you to throw something into it.

When the page is first loaded we need to check if the notepad contents has been saved from some previous visit by this browser and if so, use the stored value to replace the inner contents of the list. This can be done with the following JavaScript statement:

  if ( localStorage.getItem('notepad') ) {
    var notepad = document.getElementById('notepad');
    notepad.innerHTML = localStorage.getItem('notepad');
  }

Note that there’s no conflict in the three uses of ‘notepad’ in the code above. The name for the local variable can be anything as can the name of the stored data item. Neither has to be the same as the UL element’s ID. Hopefully, I’m avoiding confusion by naming everything ‘notepad’ and not adding any.

Since this is only going to work on some browsers, let’s test to see if local storage is available. If it isn’t,  we can just hide the the button that makes the notepad visible.

if (!window.localStorage) $('#notepad_toggle').hide();

or, for debugging, we can call an alert message.

All of the code can go into a script element embedded in the content body, like this blog post, for example:


Click the button above and enter anything in the light yellow notepad that opens in the top right corner of your HTML5 capable browser. Enter anything you want – I’ll never see it, nor will anyone else. What’s entered in your local storage stays in your local storage. Try dragging and dropping images, tables, links and other thingys. Notice something interesting? You can’t use HTML to markup your own typing but anything you drag or paste in retains all of its HTML formatting. Now Go Away! Come back to this page sometime later (with the same browser) and click the notepad button again. There’s your stuff!

Click here to see the code for a stand-alone demo to get you started.

Ron Egatz and I go back to the time before the Web. He is one of those all-around creatives who does writing, editing, photography, graphic design and some Web programming. He occasionally calls on me to solve some of the more technical problems he encounters. So I was pleased when he asked me to help one of his associates, Matt Hill of MAC Group, who needed a blog repaired ASAP.

Someone had started a blog for Profoto-USA using a customized theme but left it an unfinished mess. The sidebar was all screwed up, the more tag wasn’t working, there were no social-sharing functions and no control over the main menu – to name just a few of the problems. Profoto-USA is about the importance of good photographic lighting with dozens of interesting articles (some of the best authored by Ron) illustrated with beautiful photographs. Please click the screenshot below to check it out.

Screen shot of Profoto-USA home page Fixing the sidebar, installing social sharing widgets and enabling the WP 3.0 menu manager was straight forward. The real challenge was finding a way to give authors more control over the content. The more tag, mentioned above, provides the ability to place a marker in a post so that on the blog’s front page, the post is displayed up to the marker, followed by a link to the rest of the article. I got that working but it wasn’t enough to manage the huge amount of content. The beginning paragraphs of a post often do not make the best summary, especially with long magazine-style articles. WordPress provides the ability to hand-craft a article summary, called an excerpt, but this feature has to be coded into the theme. Some themes show post excerpts on their front page; some show full posts (up to the first more tag.) I decided to give Profoto-USA the choice of which to use on a per-post basis using a custom field.

The previous developer had hard-coded a modified Recent Posts sidebar widget that showed, for each post, the post title and a linked thumbnail image. The thumbnails are large: 304 x 190 pixels, and only the first two or three appeared “above the fold.” The obvious solution was to use a sideshow plugin that cycled through the thumbnail photographs. Now, I’ve used a number of such plugins before and the general problem with them is that they only do what the plugin author designed them to do plus whatever user configurable options that author cares to code in. Imho – most of them fall short. Since most of the code for fetching the post data was already working, I decided to use some jQuery to add the animation effects and navigation controls to make it into a sideshow (click for nerdy technical details.)

This took much less time than I anticipated – less time than it would have taken to find and configure a plugin to the client’s specifications. With the extra time on my hands, I decided to give Profoto-USA a feature they didn’t ask for but felt the site definitely needed: an index to all articles showing only the permalinked titles and the meta-info line with author and publication date. I added it to the footer menu without telling them about it.

onPhilanthropy.comI just finished a major project for Tom Watson, author of CauseWired, converting his website, onPhilanthropy.com, from a custom CMS to WordPress. The new site is built on the Arthemia Premium theme with modifications enabling it to carry ads from multiple sources.

This site was a blast to work on. I had done a couple of other small repair and rescue jobs for Tom. He is wonderful client; tech-savvy and patient, he pushed for solutions that stretched my skill set and forced me to learn new techniques. Some of the interesting features of onPhilanthropy.com include: customized widget headings, a revamped advertising manager, a Twitter slurp and feeds from companion sites such as, DotOrgJobs.com.

If you are in the dot-org space, please visit onPhilanthropy and check out how good technology can advance good causes. And, of course, feedback is always welcomed.

There’s a fundamental conflict in web page design between content and clutter. We want more content to make our pages findable & provide value to visitors while maintaining visually clear layouts so as not to frighten away seekers of simple truths. The key to solving this conundrum is to stop thinking of web pages as printed page emulators. A printed page is a fixed matrix of tiny colored dots (pixels) on a two-dimensional surface. A web page is a dynamic document object composed of multiple layers of interactive elements.

My client, Kate Nasser – the people skills coach, has grown her consulting business by consistently adding content to her blog/website and by using Twitter, LinkedIn and youTube to draw traffic. A recent SEO/SEM assessment of her site recommended adding more keyword-rich content and reducing some of front page’s  clutter.  This is what the page looked liked.

Advanced Tooltips.

We had a box on the right side of the content area listing a dozen “Needs” linked to different site pages or posts. With each need there was an associated comment (technically, a definition list.) We decided to move the box to the left side of the page (ahead of the straight text content,) placing the comment parts in tooltip boxes that appear as you mouse over the topic part. Kate was free to add more content to the hidden (only from humans) comment parts.

Tooltips are the little yellow boxes that appear when your mouse hovers over a link. The content of the tooltip box is taken from the title attribute of the HTML tag that creates the link. But ordinary tooltips are boring with fixed style and color; yellow wasn’t the best choice given the site’s aqua tones.

So, I installed JQuery Tools from Flowplayer.org which has an easy to use, advanced tooltip tool. JQuery is a library of Javascript functions that make it easy to add dynamic behavior to Web page elements without having to worry about cross-browser incompatibilities. JQuery Tools is a free, lightweight tool collection that provides basic behaviors to attach to any page element. The Advanced Tooltip tool replaces the browser’s builtin tooltip and can be attached to any page element, not just links.

To make Advanced Tooltips work, you have to provide a page element with a unique id to hold the content. It doesn’t matter where it’s placed. The element, typically a division, is dynamically positioned near the moused-over element. The element is re-useable; you only need one holder element for all tooltips of a given style on a page. The tooltip is styled using Normal CSS so I was able to match the colors and typography of that section of the site’s front page.

Technical Details (Expand)

Random Quotes

Kate has a bunch of her own quotes and was updating her front page every few days with a new quote from the collection. She asked if there were some way to automate the process. I browsed the various code and plugin collections and found noting simple or suitable. I decided to write my own.

I copied her front page as a new draft page and cloned the default page template and assigned it to the new page. Thus, I was able to work on and test the new features without endangering the site’s current front page. The cloned template would contain custom code to randomly pick a quote and place it at the beginning of the content area. The quotes themselves would be stored (and editable) as custom fields for that page with the key, “quote”.

<?php
    $todaysquote = '';
    $quotes = get_post_meta('2', 'quote');
    if (!empty($quotes)) {
        $todaysquote = $quotes[rand(0, sizeof($quotes) - 1)];
    }
?>
<div class="dailyquote">&ldquo;<?php _e($todaysquote); ?>&rdquo;
<span>&mdash;Kate Nasser</span></div>

First, a PHP variable, $todaysquote, is initialized. Then the WordPress function, get_post_meta(), gets all custom fields from post number 2 (that’s the front page) with key = ‘quote’. The values are returned as an array of strings and assigned to the variable, $quotes. If it’s not empty, the built-in, PHP random number generator picks one of its array items. Finally, the last two lines define the HTML division element that will hold the quote,  enclosing it in smart quote marks and adding Kate’s signature. Note the use of the special echo function,  _e($todaysquote),  to encode any HTML characters that might be in the quote string.

One of the upsides of this technique is that a new front page is seen in most every visit to the front page including those by search engine robots. Over time, this can expand the number of keywords associated with the page. Unfortunately, there’s no easy way to measure which quotes work best. If you do add random content like this to a page, you should check to see if you have a caching plug-in active. You might want to exclude that page from the cache.

I added this feature as a template hack because my client only wanted it on one page which already had a customized template. It could be easily generalized and added as a filter to the theme’s functions file, for example, to append a random quote to post content when generating a single-post view.

 

AirSafetyAndLawAir Safety And Law is intended to serve as a forum for the legal community to discuss air travel safety and liability issues. The blog is a project of Kreindler & Kreindler, the law firm that handles most of the major aviation accidents. I originally worked on this in late 2007 with my graphics designer friend, David Schiffer, who provided the header image and selected the theme from several sample templates I presented. We put up a demo version on WordPress.com, but not until recently have they decided to bring it live.  I moved the content to David’s managed server so that we’d be able to do robust search engine optimization and accommodate some modifications that would not be possible on WordPress.com.

As with another law firm blog I recently built, the Air Safety And Law authors wanted thumbnail versions of their portrait photos to appear with the articles they published.  Instead of hacking the template files as I had done with the previous site, however, I formalized the technique and wrote a WordPress filter. Read my recent article on how this works.

your_photo_hereThe request was simple enough. I had just built a WordPress blog for a law firm and now they wanted to have their thumbnail photos in the articles they write. I had done this for another website (also a law firm) a year ago, modifying each of the theme’s templates that displayed posts but, when I went back and looked at that code, I thought, “Too messy, there’s got to be a better way.”

A plug-in search turned up nothing. No surprise—Wordpress does not support user profile pictures natively. There’s no field in the database for an user’s image file name. Then I remembered reading an article in Smashing Magazine about filters a couple of months ago. They had an example where a subscribe request was appended to the end of each post’s content. Maybe that technique would work to prepend a photo.

In WordPress, a filter is like a plug-in except for two important distinctions: It’s not packaged for distribution and it’s associated with the theme. That is, you can’t manage the filter from the dashboard’s plug-in manager and, if you change themes, it disappears. That was all right for my purposes. The clients were quite happy with the theme we’d chosen – Mistylook, by Sadish Bala – and I could provide instructions on how to remove the filter from the theme’s functions file should they ever want to “deactivate” the feature.

I got the images from the client for the four lawyer/authors—a wallet-sized image and a thumbnail for each. The larger image would appear on the author’s profile page and the thumbnails would be placed at the beginning of their posts, floated left of the text. For the larger image, I modified the author’s template (author.php) as I had with the previous website. For the thumbnails, I would use the filter approach since post content is accessed in several templates and I wanted a unified solution. For the sake of brevity, I’ll skip the part about the author template mods in this article. If you’re interested in that piece, leave a comment and I’ll write another article.

I created a new directory, /wp-content/authors for the larger images and a sub-directory, /wp-content/authors/thumbs for the smaller versions. In each, I renamed the images files to match the corresponding login usernames. If, for example, there was a user with the login username of ‘bobama’, then the two images files would be: /wp-content/authors/bobama.jpg and  /wp-content/authors/thumbs/bobama.jpg . I did this with an ftp program but you can use the dashboard’s Media manager, in which case, the image files will be somewhere in your /wp-content/uploads directory with your other media files. All of the other work described in this article can be done through the dashboard’s theme editor by an admin user but I highly recommend using a good code editor with color syntax highlighting. BBEdit is my favorite.

A WordPress filter goes into the theme’s functions file (functions.php) and consists of two parts: A function definition and a call to add that function to a named WordPress “hook”. I called my function: add_author_photo() and  added it to the ‘the_content’ hook. You can think of this hook as the point in the page building process when WordPress gets the page or post content from the database and starts to get it in shape for the web page it’s building. WordPress passes the content to the function as a string and expects it back in return. Roughly, the outline of the process looks like this:

<?php
     function add_author_photo($content) {
         ...
         return $content;
     }
     add_filter('the_content', 'add_author_photo');
?>

Note how the entire filter is enclosed in a PHP container. This is important!  Now, all we need to do is fill in the “dots”.

First, we need to make sure that our function does its work in the right place since it will be called anytime WordPress fetches the content from the database. We want the thumbnail photo to appear in posts on the home page and on single post pages, but not on static pages (which are, in a sense, “authorless”) nor on the archive and search result pages and especially not in RSS feeds. The following if statement does what we want:

if (is_home() || is_single()) {
    ...
}

Next, the code needs to check that the image file we want for the current post author actually exists. The client may add more authors and contributors before their photos are available and we don’t want an ugly, empty missing-image square to appear where a nice photo is expected. This is a bit tricky. There’s a PHP function, file_exists(), for checking whether a file exists or not but it takes, as its argument, the full Unix path to the file, as opposed to a URL fragment. WordPress provides a function for doing this: get_theme_root() which returns a string that, depending on your hosting company’s site configuration, might look like this:

/var/web/clients/abc.com/htdocs/wp-content/themes

Since my ‘authors’ directory is at the same level in /wp-content as the themes directory, all I have to do is replace the ‘themes’ part in the string above with ‘authors/thumbs/’ and append the image’s file name. The following two lines of code will assign the username to a variable and do the replacement using  PHP’s  str_replace() function.

$author_uname = get_the_author_meta('user_login');
$author_photo = str_replace(
                    'themes',
                    'authors/thumbs/' . $author_uname . '.jpg',
                    get_theme_root() );

We can check whether the file exists with another if statement:

if (file_exists($author_photo)) {
    ...
}

Now we are ready to add the image tag to the beginning of the post content. I’ll add a CSS class, ‘authorImage’, to the image tag which I’ll use to make the image float left and set appropriate margins and padding (see below.) I’ll also enclose the image in an anchor tag that links the image to the author’s profile page. I’ve laid this out here in several lines for readability. The dot at the end of each line is the PHP concatenation operator.

$image_src = '/wp-content/authors/thumbs/' .
             $author_uname . '.jpg';

$content =  '<a href="/author/' .
            $author_uname .
            '"><img class="authorImage" src="' .
            $image_src .
            '" alt="' .
            get_the_author() .
            '" /></a>' .
            $content;

Here’s a screenshot of the final code I pasted into the theme’s functions file. Because I’m a nice guy, I added  /* comments */ to explain what was going on. Click on the image to open a text division with the actual code you can copy.

[RAW]

Click for text version

[/RAW]

The final version took a bit of debugging to fix some stupid typing errors but it worked as I wanted it to. A look at the source code for the home page shows the generated image tag and link:

<a href="/author/larryaronson"><img class="authorImage"
   src="/wp-content/authors/thumbs/larryaronson.jpg"
   alt="Larry Aronson" /></a>

All that remained was adding some simple CSS to the style sheet to float the image to the left of the post text. The rules shown below does that and sets appropriate margins.  The images already incorporated a border so I removed the border set elsewhere in the CSS and removed the drop shadow background that Mistylook adds to images as a matter of taste.

img.authorImage {
   float: left;
   margin: 0 1em 0 0;
   border: 0;
   padding: 0;
   background-image: none;
 }

That’s it. I hope you found this article useful. Suggestions for improvements are welcome.

Gregory Poe's Federal Criminal Practice BlogI just completed another WordPress blog for a client of my good friend and associate, David Schiffer, of DLS Design. David built a beautiful, static site for Gregory Poe, a lawyer in federal criminal law practice, and trusted me to copy his look and feel for the dynamic blog section. The static part of the site featured variable-width left and right margins with an image mapped navigation bar, so I selected my favorite variable-width theme, Minimal, and reconfigured his menu as a WordPress style list so that any new pages Gregory created in WordPress would be automatically added to the navigation elements.

Once Gregory started posting on blog.gpoelaw.com, we realized that his style of writing detailed legalese needed some additional typographic punch so we darkened the text and block justified the paragraphs for additional readability. Under the hood, I added my standard mix of plugins for SEO, Google Analytics and advanced editing.

President Obama gave a great speech to Congress a week ago, following up with a with even a stronger defense of his health care ideas yesterday in a speech to the AFL-CIO. Great arguments, great passion and a great show of resolve. Not much change, however; not even close to the kind of change I voted for. Don’t get me wrong. I strongly support health insurance reform, but the president and congress will bring no sanity to a needlessly complex, expensive and cruel system.

I was disappointed that the president ducked the opportunity to define American Health Care and instead left us with a mish-mash of fixes to the current system. Reform is not in the details, Mr. Obama; it requires rethinking of the issue; seeing the big picture. By failing to set a defining base of what health care can and should be, the president has played right into the hands of those who profit most from preserving the status quo.

Alternative Visions of Health Care

Health care can be thought of as infrastructure. Like our interstate highway system, it promotes our defense and progress as a nation. We need healthy people to defend our land and to provide the spirit and energy that promotes innovation and competition. That provides a great practical argument for expanding existing insurance programs to cover everyone. There are a number of different ways to structure this. The basic idea is that your health is a vital national interest; not just something useful to a full-time employer.

But we can do better. I believe that good health should be declared a constitutional right. Like privacy, it is a necessary condition for “life, liberty and the pursuit of happiness.” In order to protect that right, the government has a responsibility to insure that all of its citizens have access to good health care.

No one should die because they cannot afford health care, no one should go broke because they get sick, and no one’s child should miss a doctor’s appointment because it costs too much.

Let’s add that everyone should get good preventive care to prevent disease before expensive treatment becomes necessary. I’m talking about free, regular medical checkups for everyone! Then a combination of public and reformed private insurance to cover the costs of hospital stays, surgeries, therapy and long term disability.

Can we afford this? Yes! Of course we can. Done right, cost savings and productivity gains will be huge. But even so, what’s so wrong with raising some taxes; or perhaps, ending one of our very expensive wars.

Older Posts »