Tag: kranthi

Automatic line breaks in narrow columns with CSS 3 hyphens and word-wrap

A problem that has always existed but has become more common lately as more people – thanks to the popularity of responsive web design – make their layouts adapt to narrow viewports, is the lack of automatic hyphenation in web browsers.

As columns of text become narrower, the risk of a single word being longer than the column width increases. When that happens, the text normally extends outside the column (unless the column element’s overflow property has been given a different value than the default visible). The effect can be anything from just a slight visual glitch to unreadable text. Either way it’s something you don’t want to happen.

Read full post

Posted in .

Copyright © Roger Johansson



Stop Shouting. Start Teaching.


  

Imagine you are in a classroom. Let’s say a high school classroom. You’re sitting at your desk, listening to your favorite teacher—the one who inspired you, the one who got you excited about that thing you love for the first time.

You’ve stopped taking notes because your body just can’t quite function normally when your mind is being blown. You don’t feel the pen in your hand, or the surface of the desk under your arms. You’re somewhere in between your body and the blackboard. That’s the magic of learning; it’s transportational.

Now, deep breath.

Back to reality.

Perhaps your learning experiences were not like this, but I hope they were. And if they were, did it ever occur to you in those moments that you were being sold something? That the moment was approaching when you’d be asked to sign on the dotted line or open your wallet? When you’d kick yourself for being fooled into thinking that your teacher was offering something to you for free? When you’d learn to stifle the desire and ability to trust someone?

Of course not. What you received came without strings attached; it was a free gift of knowledge to change you, to shape you, to edify you. Not to compel you to buy something.

After all, your teacher wasn’t a marketer.

Right?

Or, was he?

It’s worth asking at this point: What, exactly, is marketing? Here I won’t quote a definition—not just because we’re all capable of looking it up ourselves, but because it really doesn’t matter anymore what the “official” definition of marketing is. Marketing, in its ubiquity, is something we all live and breath. We know what it is, though we may struggle with articulating it with any meaningful precision. In our culture, the distance between marketing and creativity is virtually nonexistent.

Every bit of that space has been filled with the promotional. What were once barely overlapping magisteria have become fully integrated. It’s not enough that we make beautiful things, or have brilliant ideas, or even have powerful experiences anymore; they’re hardly real to the world until they’ve been shared in some digital burst of “Here I am, you should pay attention to me.”

Stop Shouting. Start Teaching 2

Life and work has become noisy with marketing. And the noisier it gets, the noisier it gets, because we’ve bought into the lie that nothing cuts through noise better than the right kind of noise. But noisy marketing—of the parade for a naked emperor kind—is cheap; there is no there there, and we all end up feeling cheap for looking, anyway.

There is a better way, of course. But the better way requires that we get as far away from this sort of marketing as possible. In fact, it might be better that we call it something else entirely, because no one ever says, “I want to be a marketer when I grow up.” So, why not call it education? If you ever experienced the free gift of education—whether or not as I dramatized it above—let that be your model for marketing. For your sake; for the sake of all of us.

Inception

Disparaging marketing is easy, isn’t it? What I just wrote came naturally; it flowed out of my experience struggling with my own value for privacy and the frequency with which it is violated, coupled with my job representing a company and the frequency with which I have to market our services. I know the kind of marketing I don’t like, and to do it differently is easier said than done. Frankly, it’s just far easier to do marketing than to have marketing done to you. Yet, there is no Golden Rule for marketing—market unto those as you would have them market unto you. Shouldn’t there be such a rule? There can be.

It starts with doing something good.

Quality

There is nothing wrong with selling things, or even with making lots of money selling things. There is something wrong, though, with selling a product or service that you know is not worth its price. So there are some questions we must ask if we are to follow any “golden rule” of marketing: Do I believe in what I’m selling? Is it good for people? Is it worth what I am asking people to pay for it?

Stop Shouting. Start Teaching 3

Could you imagine a teacher answering “No” to any of these questions? “No, I don’t believe in what I teach.” “No, what I teach is not good for people.” “No, what I teach isn’t worth the time my class requires.” Could any teacher with integrity answer no to these questions and still manage to show up for class every Monday morning? I doubt it.

Alan Jacobs, writing for The Atlantic about the role of quality in the shifting sands of business success, had this to say:

“What goes around comes around; what goes up must come down. Microsoft has been gradually drifting to the margins of our tech consciousness; Google is scrambling to find a way to compete with Facebook. Everything moves faster in a wired world, including the pace of change in business… A decade from now the landscape of the technology business will sure look very different than it does today. Maybe by 2022 Apple and Amazon will be marginal companies once again—underdogs that I can feel good about supporting.”

What shifts the sands of the business landscape isn’t marketing, it’s quality. Apple rose to the top because it made outstanding products, not “just fine” ones with outstanding advertising. Microsoft, on the other hand, stumbled not because its advertising is terrible—though it really is—but because its products weren’t very good, either. And as for Amazon, Amazon rose to the top by offering a level of service that shocked shoppers: an easy to navigate store, with an unfathomably large inventory, and delivery that exceeded anyone’s reasonable expectations for speed. It reset those expectations.

If Amazon fails, it will fail because either someone else comes along who can do better—unlikely as that may be—or because we decide that we don’t feel comfortable with the costs of the level of service they offer. Many right now are already questioning that, whether inexpensive and immediate delivery are worth the working conditions that make it possible. Marketing will probably try to change our minds. It may even work on some of us, for a little while. But if failure is to be avoided, marketing will have little to do with it.

If you can do something truly good, you won’t have much of a marketing challenge. If you can keep doing something good without something bad subsidizing it, marketing will take care of itself.

Positioning

But what if someone else does exactly the same thing you do? What if you can’t beat their price? What if you can’t outserve them? This is typically where “savvy” marketing comes in. When labels carry claims that either overemphasize a non-differentiator so that it seems like one, or straight up lie.

Stop Shouting. Start Teaching 4

Imagine the educational corollary: “The same easy A, now with twice the History!” or “Become a Quantum Physicist, Results Guaranteed!” Preposterous.

It’s a whole lot easier to avoid resorting to manipulation if you don’t have any real competitors. Competitors force each other to make less meaningful but more manipulative distinctions between one another. If you think you’ve got the “good” thing down, consider your positioning. Are you actually different? If not, how will you survive without being sleazy?

Attract, Inform, Engage

So, let’s say you’ve got the quality and positioning stuff worked out. You do something good that nobody else does. Fantastic. That is, assuming people know about you. Taking a Field of Dreams approach—if you build it, they will come—won’t work. If you build it, and they know about it, they will come. But even if they come, you’ve got to make sure they understand what it is that they’re coming for. And then you’ve got to make them want to stick around. This is a three-step process: attracting prospects, properly informing them, engaging with them. That is what marketing should be all about. Attract, inform, engage; not attract, mislead, compel.

If you are well positioned, attraction is much easier. Imagine three hot-dog vendors at a baseball game. Two wander up and down the stands, shouting, “Hot dogs! Get your delicious hot dogs here!” Their success is going to come down to luck—who happens to be closest to the right people. But the third vendor sticks to the low seats. He’s shouting, too, except he’s got different dogs to sell: “Low-fat hot dogs! Eat two for the fat of one!” Now who do you think will have an easier time selling hot dogs? The more specific your audience is, the easier it is to attract them.

If you can attract a specific audience, informing is easy, too. You already know something about them and what they need. If you have a worthy solution to that need, all you have to do is tell them about it. That’s where the teaching comes in: Start generally—Introduction to Your Problem, then Our Solution 101—and be prepared to give them more detail as they need it. Incrementally informing, by the way, will also take care of engagement. Give them some, they’ll want more. Ask any engaged student sitting in Advanced Trigonometry 3 why they are there and you’ll likely hear many similar answers, all having to do with being attracted and informed by someone special back in their beginner days.

Know Your Role

If you make things, it’s difficult to avoid marketing. But if you can do it the good way—attracting, informing, and engaging—to serve that good thing you do, then that thing we’ve wanted to avoid no longer looks so bad. And even then, “marketer” is just one of many roles that people who make things play in some capacity. But it’s a role that should always be subservient to your primary one: making and doing good things. To keep that role connected to the good things we do, I’ve used teaching as a metaphor.

I know it’s abstract, but if there is one single characteristic of good teachers that could stand to make everything we do—as well as how we market it—better, it’s caring. Good teachers care. They care about the material. They care about how they teach it. They care about their students. If we care too—about what we do, how we do it, and who we do it for—then we’ll be OK.

Resisting the Dark Side

That’s the setup, anyway. But caring is hard. Caring requires a commitment to resisting the very things that currently seem to drive the culture of marketing—things like haste, deception, and even your own ego.

Stop Shouting. Start Teaching 5

Slow Down

Slow down, please. Not everything needs to be right now. One thing I like to say that usually riles people up is that there are no marketing emergencies. Really. If there are, it’s because somebody screwed up or somebody’s expectations are out of whack.

But that doesn’t change the fact that other people feel differently. Open your email account and watch it fill before your eyes. Open Twitter and watch the nonstop flow of information push down your timeline. It’s incredible how rapid-fire online culture has become, and naturally, how marketing has followed suit. As marketing has become so predominantly digital, speed has become a defining characteristic of the experience. But when your blood pressure rises and you feel the anxiety of falling behind—that you should be blogging more, tweeting more, posting more on Facebook, Pinterest, and the like—ask yourself this: How good can it be if you’re producing so much of it so often?

Honesty

Honesty is the enemy of traditional marketing. It’s sad but true. It’s not because honesty isn’t possible in marketing, but that if companies were completely honest about their products and services—about how they’re made, what they do, their flaws, their shelf life, etc.—fewer people would buy them. That’s why creating illusions is so essential to marketing. But it only takes a tiny crack in the surface to destroy an illusion. As a colleague pointed out to me recently, a supermodel only has to stumble once before the illusions so central to fashion fall away and you are left with just people wearing clothes. If the quality is there, there is nothing to hide.

Stop Shouting. Start Teaching. 6

That’s the big-picture, but I think most honesty-erosion tends to happen on a smaller scale, where the line between truth and fiction can be pretty blurry. There’s a general impulse toward bending that line intentionally, one often motivated by our desire to bring attention to something we believe deserves it. Whether it’s a product, a service, or even a cause, we might be willing to “sex up the story” if doing so means bringing greater awareness to it.

This isn’t just a marketing problem, by the way. We do it when we believe the attention garnered by a thing or an idea or an injustice isn’t as big as it should be. Listen to the retraction issued by This American Life of Mike Daisy’s account of working conditions in Apple’s factories in China. Pay attention to how uncomfortable you feel. That discomfort is a measure of the distance between truth and fiction.

For the first year after graduating from college, I did freelance design work. I registered a business, created business cards, set up a website, the works. I wasn’t alone, either. Several classmates did the same thing, and we would often compare notes and even help each other get work from time to time. We learned all kinds of things by trial and error back then, but the one thing that left the greatest impression upon me had to do with how honest we were in describing ourselves. Every one of us made heavy use of the word “we” on our websites—though “we” was almost always just one person working from a room in a shared apartment—because we feared we wouldn’t be hired if it was clear that “we” was really “I,” a freelancer flying solo.

We believed that no matter how good our work was, we’d be ignored as individuals. So we created an illusion that we thought looked strong. “I” was just a kid on my laptop at a desk in his bedroom; “We” was a company, confident, experienced, secure. But that, of course, wasn’t true. I learned that there was no point in trying to convince potential clients of something other than that which would quickly become clear to them if they hired me. So, a simple rule: If you’re one person, never refer to yourself as “we.” That’s the kind of small-scale honesty we need to take seriously.

In, but not of

But let’s be realistic. Even if you change, you can’t expect everyone else to change too. It’s certainly possible that if enough people embrace a new way of doing things, the culture might shift overall, but that is unlikely to happen overnight.

The culture of online marketing is unhealthy—the lack of criticism of it is pretty astonishing to me—but the real tragedy is watching the forces of self preservation turn good people with good intentions into obnoxious, self-aggrandizing loudmouths that collect into BS echo chambers. Sometimes what you see accepted or celebrated around you is exactly what you shouldn’t do. I liked how Oliver Reichenstein put it in a post-SXSW tweet:

“Studied the SXSW talks to find out what not do as a speaker: 1. Don’t think you’re cool 2. Don’t preach 3. Don’t sell. 4. No false modesty.”

Why do we feel that the only way to survive is to do things like everyone else does? There’s no good reason for it. In fact, we’re all waiting for someone to pave the way for us by having the courage we don’t have, the courage to do something different. Why can’t you be one of those people? When it comes to doing the right thing, don’t wait for someone else’s courage to stand in for your own.

Ground control to _____

Remember those clumsy supermodels? They do us a favor when they stumble. They bring us back down to Earth, where we’re all just people wearing clothes. No matter how important we think we are, or how important we think the things we make or do are, we could all stand to stumble down the runway every once in a while. Especially when it comes to marketing.

Stop Shouting. Start Teaching. 7

A great example of this came in the recent blow-up over “Homeless Hotspots,” a campaign created by BBH (a marketing firm) that turned the homeless of Austin into roaming internet access points available to the throngs attending the South by Southwest conference. Needless to say, it was controversial. Plenty has been said about it—both in support and in criticism—but amidst the noise, one comment written by Thomas Wendt resonated most for me:

“In the end, everyone is full of shit—supporters and detractors—and it’s all a result of spectacle and denial. The entire system creates such dissonance that we lash out against it. We’re unable to reconcile the differences between image and the real, altruism and self-interest, trust and deception. So we gravitate toward poles: BBH is a charitable company or BBH is a lying capitalist institution. Of course, the truth in somewhere in between, but denial and self-deception keeps us from admitting it.”

Wendt’s post was titled, Staring Down the Spectacle, which really gets at the point: It is the culture—and the spectacle it creates—that is your adversary, not any specific action per se, nor any other person. Yet culture has a profound power to shape each of us, so just as much as we should scrutinize what we observe around us, we should bring equal scrutiny to what we observe within ourselves. When it comes to marketing, the most meaningful question I can ask at any point is, just how full of shit am I?

Guilty as Charged

I wrote this as an act of resistance, as a way of keeping myself from disappearing into the “dark side,” not as a prophet condemning from atop a mountain. I see myself struggling to maintain the integrity of an educational marketing model and I often don’t like what I see. But, I’ve also discovered that we must intentionally learn from examples—both good and bad ones. The bad ones are easy to study. We’re all close enough to them to do it. We’re among them. We may even be one of them. The question is whether we’re willing to do something about it.

(il)


© Christopher Butler for Smashing Magazine, 2012.


Mental Model Diagrams (Cartoon)


  

We tend to carefully create our HTML and CSS, and meticulously place every pixel to our designs. We plan exactly where our content should be placed on a particular site. Among many other decisions we need to make, we always keep in mind to craft a great experience for all our users. But how do we know what our users really want?

One way is to understand the motivations that drive users in general. A mental model diagram can be created to do just that—to dive deeper and discover what users are trying to accomplish, and then create solutions that match.

In this comic, Indi and Brad introduce mental model diagrams to us and how we can use them to build better websites. You can also view a larger version of the comic here.

Mental Model Diagrams

Feel free to share your thoughts on mental model diagrams in the comments section below.

(il)


© Indi Young and Brad Colbow for Smashing Magazine, 2012.


Decoupling HTML From CSS


  

For years, the Web standards community has talked about the separation of concerns. Separate your CSS from your JavaScript from your HTML. We all do that, right? CSS goes into its own file; JavaScript goes in another; HTML is left by itself, nice and clean.

CSS Zen Garden proved that we can alter a design into a myriad of permutations simply by changing the CSS. However, we’ve rarely seen the flip side of this — the side that is more likely to occur in a project: the HTML changes. We modify the HTML and then have to go back and revise any CSS that goes with it.

In this way, we haven’t really separated the two, have we? We have to make our changes in two places.

Exploring Approaches

Over the course of my career, I’ve had the pleasure and privilege to work on hundreds of different websites and Web applications. For the vast majority of these projects, I was the sole developer building out the HTML and CSS. I developed a way of coding websites that worked well for me.

Most recently, I spent two years at Yahoo working on Mail, Messenger, Calendar and other projects. Working on a much larger project with a much larger team was a great experience. A small team of prototypers worked with a larger team of designers to build out all of the HTML and CSS for multiple teams of engineers.

It was the largest-scale project I had worked on in many aspects:

  • Yahoo’s user base is massive. Mail alone has about 300 million users.
  • Hundreds of people spread across multiple teams were working with the HTML and CSS.
  • We were developing a system of components to work across multiple projects.

It was during my time at Yahoo that I began to really examine how I and the team at Yahoo build websites. What pain points did we keep running into, and how could we avoid them?

I looked to see what everyone else was doing. I looked at Nicole Sullivan’s Object-Oriented CSS, Jina Bolton’s presentation on “CSS Workflow� and Natalie Downe’s “Practical, Maintainable CSS,� to name just a few.

I ended up writing my thoughts as a long-form style guide named “Scalable and Modular Architecture for CSS.� That sounds wordy, so you can just call it SMACSS (pronounced “smacks�) for short. It’s a guide that continues to evolve as I refine and expand on ways to approach CSS development.

As a result of this exploration, I’ve noticed that designers (including me) traditionally write CSS that is deeply tied to the HTML that it is designed to style. How do we begin to decouple the two for more flexible development with less refactoring?

In other words, how do we avoid throwing !important at everything or falling into selector hell?

Reusing Styles

In the old days, we wrapped font tags and applied background attributes to every HTML element that needed styling. This was, of course, very impractical, and thus CSS was born. CSS enabled us to reuse styles from one part of the page on another.

For example, a navigation menu has a list of items that all look the same. Repeating inline styles on each item wouldn’t be practical. As a result, we begin to see CSS like this:

#nav {
   margin: 0;
   padding: 0;
   list-style: none;
}

#nav li {
   float: left;
}

#nav li a {
   display: block;
   padding: 5px 10px;
   background-color: blue;
}

Sure beats adding float:left to every list item and display:block; padding:5px 10px; to every link. Efficiency, for the win! Just looking at this, you can see the HTML structure that is expected:

<ul id="nav">
   <li><a href="/">Home</a></li>
   <li><a href="/products">Products</a></li>
   <li><a href="/contact">Contact Us</a></li>
</ul>

Now, the client comes back and says, “I want a drop-down menu to appear when the user clicks on ‘Products.’ Give them easy access to each of the pages!� As a result, our HTML changes.

<ul id="nav">
   <li><a href="/">Home</a></li>
   <li><a href="/products">Products</a>
      <ul>
         <li><a href="/products/shoes">Shoes</a></li>
         <li><a href="/products/jackets">Jackets</a></li>
      </ul>
   </li>
   <li><a href="/contact">Contact Us</a></li>
</ul>

We now have a list item within a list item, and links within it. Our menu has a horizontal navigation when the client wants a vertical list, so we add some rules to style the inner list to match what the client wants.

#nav ul {
   margin: 0;
   padding:0;
   list-style:none;
}

#nav li li {
   float: none;
}

#nav li li a {
   padding: 2px;
   background-color: red;
}

Problem solved! Sort of.

Reducing The Depth Of Applicability

Probably the most common problem with CSS is managing specificity. Multiple CSS rules compete in styling a particular element on the page. With our menu, our initial rules were styling the list items and the links in the navigation and the menu. Not good.

By adding more element selectors, we were able to increase specificity and have our menu styles win out over the navigation styles.

However, this can become a game of cat and mouse as a project increases in complexity. Instead, we should be limiting the impact of CSS. Navigation styles should apply to and affect only the elements that pertain to it, and menu styles should apply to and affect only the elements that pertain to it.

I refer to this impact in SMACSS as the “depth of applicability.� It’s the depth at which a particular rule set impacts the elements around it. For example, a style like #nav li a, when given an HTML structure that includes our menus, has a depth of 5: from the ul to the li to the ul to the li to the a.

The deeper the level of applicability, the more impact the styles can have on the HTML and the more tightly coupled the HTML is to the CSS.

The goal of more manageable CSS — especially in larger projects — is to limit the depth of applicability. In other words, write CSS to affect only the elements that we want them to affect.

Child Selectors

One tool for limiting the scope of CSS is the child selector (>). If you no longer have to worry about Internet Explorer 6 (and, thankfully, many of us don’t), then the child selector should be a regular part of your CSS diet.

Child selectors limit the scope of selectors. Going back to our navigation example, we can use the child selector to limit the scope of the navigation so that it does not affect the menu.

#nav {
   margin: 0;
   padding: 0;
   list-style: none;
}

#nav > li {
   float: left;
}

#nav > li > a {
   display: block;
   padding: 5px 10px;
   background-color: blue;
}

For the menu, let’s add a class name to it. This will make it more descriptive and provide a base for the rest of our styles.

.menu {
   margin: 0;
   padding: 0;
   list-style: none
}

.menu > li > a {
   display: block;
   padding: 2px;
   background-color: red;
}

What we’ve done is limited the scope of our CSS and isolated two visual patterns into separate blocks of CSS: one for our navigation list and one for our menu list. We’ve taken a small step towards modularizing our code and a step towards decoupling the HTML from the CSS.

Classifying Code

Limiting the depth of applicability helps to minimize the impact that a style might have on a set of elements much deeper in the HTML. However, the other problem is that as soon as we use an element selector in our CSS, we are depending on that HTML structure never to change. In the case of our navigation and menu, it’s always a list with a bunch of list items, with a link inside each of those. There’s no flexibility to these modules.

Let’s look at an example of something else we see in many designs: a box with a heading and a block of content after it.

<div class="box">
   <h2>Sites I Like</h2>
   <ul>
      <li><a href="http://smashingmagazine.com/">Smashing Magazine</a></li>
      <li><a href="http://smacss.com/">SMACSS</a></li>
   </ul>
</div>

Let’s give it some styles.

.box {
   border: 1px solid #333;
}

.box h2 {
   margin: 0;
   padding: 5px 10px;
   border-bottom: 1px solid #333;
   background-color: #CCC;
}

.box ul {
   margin: 10px;
}

The client comes back and says, “That box is great, but can you add another one with a little blurb about the website?�

<div class="box">
   <h2>About the Site</h2>
   <p>This is my blog where I talk about only the bestest things in the whole wide world.</p>
</div>

In the previous example, a margin was given to the list to make it line up with the heading above it. With the new code example, we need to give it similar styling.

.box ul, .box p {
   margin: 10px;
}

That’ll do, assuming that the content never changes. However, the point of this exercise is to recognize that websites can and do change. Therefore, we have to be proactive and recognize that there are alternative elements we might want to use.

For greater flexibility, let’s use classes to define the different parts of this module:

.box .hd { }  /* this is our box heading */
.box .bd { }  /* this is our box body */

When applied to the HTML, it looks like this:

<div class="box">
   <h2 class="hd">About the Site</h2>
   <p class="bd">This is my blog where I talk about only the bestest things in the whole wide world.</p>
</div>

Clarifying Intent

Different elements on the page could have a heading and a body. They’re “protected� in that they’re a child selector of box. But this isn’t always as evident when we’re looking at the HTML. We should clarify that these particular hd and bd classes are for the box module.

.box .box-hd {}
.box .box-bd {}

With this improved naming convention, we don’t need to combine the selectors anymore in an attempt to namespace our CSS. Our final CSS looks like this:

.box {
border: 1px solid #333;
}

.box-hd {
margin: 0;
padding: 5px 10px;
border-bottom: 1px solid #333;
background-color: #CCC;
}

.box-bd {
   margin: 10px;
}

The bonus of this is that each of these rules affects only a single element: the element that the class is applied to. Our CSS is easier to read and easier to debug, and it’s clear what belongs to what and what it does.

It’s All Coming Undone

We’ve just seen two ways to decouple HTML from CSS:

  1. Using child selectors,
  2. Using class selectors.

In addition, we’ve seen how naming conventions allow for clearer, faster, simpler and more understandable code.

These are just a couple of the concepts that I cover in “Scalable and Modular Architecture for CSS,� and I invite you to read more.

Postscript

In addition to the resources linked to above, you may wish to look into BEM, an alternative approach to and framework for building maintainable CSS. Mark Otto has also been documenting the development of Twitter Bootstrap, including the recent article “Stop the Cascade,� which similarly discusses the need to limit the scope of styles.

(al) (il)


© Jonathan Snook for Smashing Magazine, 2012.


Random Redirection In WordPress


  

If you run an online magazine, most of your readers will never go through your archive, even if you design a neat archive page. It’s not you; it’s just that going through archives is not very popular these days. So, how do you actually make readers dig in without forcing them? How do you invite them to (re)read in a way that’s not boring? How do you make your WordPress magazine more interactive?

Have you tried random redirection?

Call it recycling if you like, but random redirection doesn’t have to be about retreading familiar territory. Through random redirection, you offer readers a chance to hop randomly through your posts and discover content that they somehow missed.

The concept really is simple. All you have to do is create a hyperlink — named, say, “Random articleâ€� — that when clicked will redirect the reader to a randomly pulled article.

WordPress supports random redirection out of the box, but it’s not very obvious. All of the required functions are in the core, but they’re not bound in any common workflow. For instance, generating a “Random article� link in the main menu simply by checking a box in the administration section is not possible.

To implement random redirection in WordPress, you will usually need to work with the following three things:

  • A page to process the redirection,
  • A query to pick a post from the database,
  • Some sort of mechanism to initiate the redirection.

Of course, many of you might want to use a plugin. That’s absolutely fine, as long as you don’t need any more features than what it offers.

You would probably come across Matt Mullenweg’s Random Redirect plugin first. Then you would probably try Random Redirect 2, which expands on that.

Instead, today I’ll guide you through a custom implementation that I use. It’s not the “right� way to implement random redirection; it’s just one plugin-less solution to start with and build on.

We’ll be working with the three things mentioned in the list further up. Let’s go into the concept in detail.

The Simple Solution

We’ll be implementing random redirection through a WordPress page, which we’ll simply call “Random.� Creating this new page in the admin section will be the last step we take, though. Why? Because we don’t want to make the redirection page accessible before it’s been fully implemented.

According to the WordPress template hierarchy, if you create a page template file named page-random.php, whenever a user loads the page assigned to the slug random, it will load through the page-random.php template. This is a well-known benefit of WordPress and is also useful for our random redirection.

The page-random.php page template will not include the usual calls for loading the header, sidebar and footer templates, because our “Random� page won’t generate any visible output for the user; it will simply jump (that is, redirect) to a randomly chosen article. Because we need to make only one request from the database (to select one random article to redirect to), we will make only one call to the get_posts() function in the template, and we’ll use a foreach loop to process the output.

The get_posts() function receives only two arguments as its input, with which we’re specifying that we want to fetch only one post randomly. The orderby argument set to rand is what enables randomization in WordPress. We don’t need to specify the post_type because it’s already set to post by default for get_posts(). We also don’t need to specify the post_status because it defaults to publish, which is exactly what we need.

// source code from page-random.php

// Random Redirection Page Template

// set arguments for get_posts()
$args = array(
    'numberposts' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = get_posts ( $args );

// process the database request through a foreach loop
foreach ( $my_random_post as $post ) {
  // redirect the user to the random post
  wp_redirect ( get_permalink ( $post->ID ) );
  exit;
}

So, we first save the data from get_posts() into a variable and then process it through the foreach loop. The magic happens in the foreach loop, when the redirection is initiated through the wp_redirect() function, which has the post’s permalink as its input.

random-redirection-wordpress-add-random-page
Creating a “Random� page through WordPress’ administration interface

Now the only thing we need to do is go to WordPress’s administration section, create a blank new page with the slug random, and publish it. Then, when you visit http://www.mywebsite.com/random/, you will be automatically redirected to a random article.

random-redirection-wordpress-add-random-page-main-menu
Adding a link to the “Random� page in the main menu.

We can now add a link in the main menu to make the page easily accessible.

Using WP_Query Instead

The implementation above can easily be adapted to directly use the WP_Query class, instead of the get_posts() function.

// source code from page-random.php implemented through WP_Query

// Random Redirection Page Template

// set arguments for WP_Query()
$args = array(
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

The main benefit of using WP_Query is that it can accept more arguments than the get_posts() function, thus offering more flexibility when you’re building specific queries.

A Few More Examples

With both get_posts() and WP_Query, we can be very specific and implement random redirection for posts of custom types or posts that belong to particular categories.

For example, we could make WordPress redirect to articles published only in the “Travel� category:

// set arguments for WP_Query()
$args = array(
    'category_name' => 'travel', // remember, we are using category slug here
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

Or we could redirect to posts from all categories except “Uncategorized�:

// set arguments for WP_Query()
$args = array(
    'category__not_in' => array(1), // id of the category to be excluded
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

How about limiting randomization to posts published in 2011?

// set arguments for WP_Query()
$args = array(
    'posts_per_page' => 1,
    'year' => '2011',
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

Maybe even add filtering by custom field? Let’s limit random redirection to posts that have a custom field with the value strawberry assigned.

// set arguments for WP_Query()
$args = array(
    'posts_per_page' => 1,
    'meta_value' => 'strawberry',
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

The example above could easily be transformed to limit random redirection to posts that have the custom field long_description assigned. Remember, our only condition here is for the post to have the custom field assigned. It doesn’t matter what the value of the long_description custom field is.

// set arguments for WP_Query()
$args = array(
    'posts_per_page' => 1,
    'meta_key' => 'long_description',
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

Instead of posts, we could also implement random redirection for pages:

// set arguments for WP_Query()
$args = array(
    'post_type' => 'page',
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

We could even create random redirection for custom post types:

// set arguments for WP_Query()
$args = array(
    'post_type' => 'my-custom-post-type',
    'posts_per_page' => 1,
    'orderby' => 'rand'
);

// get a random post from the database
$my_random_post = new WP_Query ( $args );

// process the database request through WP_Query
while ( $my_random_post->have_posts () ) {
  $my_random_post->the_post ();
  // redirect the user to the random post
  wp_redirect ( get_permalink () );
  exit;
}

As you can see from these examples, we can add a random redirection link to a WordPress website with just a few lines of code. Nothing complicated, nothing too advanced.

random-redirection-wordpress-wikipedia-wikihow

If random redirection still doesn’t make sense to you, hop on over to Wikipedia and WikiHow and see how their links to random articles work.

Play The Randomization Game!

Now that you know how easy implementing a random redirection page in WordPress is, you can start planning for your own random output.

All in all, it’s a great feature. Every online magazine should have it. It requires only a single click per request; it’s unpredictable, it’s fun, and it will be useful to your readers.

Further Reading

(al)


© Goce Mitevski for Smashing Magazine, 2012.


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