Helpful Articles

We have searched the web to bring you helpful articles.

Picturefill 2.0: Responsive Images And The Perfect Polyfill

Not since the early days of web standards have I seen our community rally around a seemingly small issue: responsive images.

Over the last four years (yeah, it’s been about four years), we’ve seen many permutations of images in responsive design. From the lazier days of setting max-width: 100% (the absolute minimum you should be doing) to more full-featured JavaScript implementations, such as Picturefill and Zurb’s data-interchange method, we’ve spent a lot of time spinning our wheels, banging our heads and screaming at the wall. I’m happy to say that our tireless journey is coming to a close. The W3C and browser makers got the hint.

The State Of Responsive Images

In our search for the holy grail of serving the right image to the user, our attitude towards browser makers until now has largely been, “Forget you — we’ll do it ourselves.” I’m certainly no exception. We were so attentive to responsive images and were exposed to all of the guesswork and trials that are not typically released to the public that we got impatient (rightfully so) and did it with JavaScript.

get link The difference between a CSS transition and a responsive image is, of course, how they degrade. If a CSS transition doesn’t work, who really cares? Your interface might be a little jumpy, but the experience as a whole won’t really suffer because your users will still be able to accomplish their goal and consume the content they need.

That really isn’t the case with images. How does a new image tag degrade? The img tag is so widely accepted that I couldn’t even find when the W3C recommended it as a standard, other than a small reference in the HTML 4.01 specification. Replacing or even expanding on the img tag would be like telling Frank Sinatra to wear a baseball cap instead of a fedora — you’ll get some pushback.

Resource Problems

As responsive design grew in popularity and as the media through which users consume information became uncontrollable, we slowly realized that img by itself wasn’t going to cut the mustard. We started asking questions like, “What screen size is the user on?” and “What’s the pixel density of the screen?” These questions fuelled our image techniques until we realized that screen size and pixel density have absolutely no relationship to the amount of bandwidth available to serve up a huge high-definition image.

The RICG began working on the picture element, sharing its work with the W3C along the way.
The RICG began working on the picture element, sharing its work with the W3C along the way.

The solutions got pretty complex. Talk of the picture element started, and a group called the Responsive Images Community Group (RICG) appeared. The RICG began working on the picture element, sharing its work with the W3C along the way. The result has led us to today and this discussion about all of the progress that’s been made.

The Introduction of srcset

Because most of the responsive-image community was on board with the picture element and looking forward to it because of the great polyfills, such as Picturefill, it went ahead and released a well thought-out and fleshed-out document outlining something called srcset, which is an extension of the standard img tag. Yeah, I know — it feels like it came out of nowhere. It was also super-complicated and overly limiting by restricting you to (implied) pixel values and using a microsyntax that didn’t allow for scalability with media queries in the future. Luckily, the syntax has matured into what we have today, which is a fairly robust recommendation.

Most recently, Andrew Clark said it best when he tweeted, “Looked at the responsive images srcset & sizes attributes for the first time. Blimey it’s complicated.”

I couldn’t have said it better myself. Let’s look at what we’re dealing with:

<img alt="dog" src="dog.jpg" srcset="dog-HD.jpg 2x, dog-narrow.jpg 300w, dog-narrow-HD.jpg 600w 2x">  

Three major attributes are in the snippet above: alt, src and srcset. The alt attribute is the same as it’s always been; src is the fallback if srcset isn’t supported; and srcset is obviously the meat and potatoes here.

We can see three arguments in srcset. The first is the image path. The second gives the browser information about the natural widths of the sources, so that it knows which resource to serve to the user (based on the user’s preferences and cross-referencing with the sizes attribute – I told you it was complicated). The last piece sets the optional pixel ratio (2x in this example specifies the high-definition image).

One thing I really love about srcset is that the specification states that the browser should contain image-allocation preferences for certain bandwidth situations. This means you don’t have to worry about serving a 2x image to a high-definition screen if that device is on a cruddy 3G connection. The user’s preferences should take over, and the browser would choose the appropriate image to serve.

Preparing for the picture Element

After much complaining about our new weird friend, srcset, the RICG continued working on the picture element, which is finally getting some serious traction with browser makers… well, that is, with Chrome. The proposed syntax for the picture element might look familiar because we saw it largely in the first version of Picturefill, and it’s not unlike how <audio> and <video> are marked up.

<picture>
  <source media="(min-width: 600px)" srcset="large-1.jpg, large-2.jpg 2x">
  <img alt="A fat dog" src="small-1.jpg">
</picture>  

As you can see, a source tag is in the picture element, along with a normal img tag. Just as we saw with src in srcset, the img is a fallback. In the source tag, we have what looks like a media query, alongside a srcset attribute that contains the same image-source and pixel-density arguments as before. This seems like a nice clean way to popularize responsive images; we’re generally familiar with the syntax, so it should be easily adopted.

Browser Support

The srcset attribute has been supported in Chrome since version 34. At the time of writing, it is not supported anywhere else. Mozilla appears to be working on an implementation (fingers crossed). Internet Explorer is nowhere in sight.

The picture element has even worse support; it isn’t even in Chrome yet. But like Mozilla with srcset, Google is currently working on implementing it. If you can stomach reading through a specification, I highly recommend it. Even though there isn’t much of a plot and the character development is pretty weak, it’s still a pretty good read.

site de rencontre les mieux Picturefill 2.0 was created because native support is reasonably close. You know we’ll need a rock-solid polyfill to use when the time officially comes, so let’s take a look at it!

Introducing Picturefill 2.0

Picturefill 2.0 was recently released as beta, and it’s quite a large jump from version 1. The RICG really aimed to create http://euromessengers.org/?biodetd=bin%C3%A4re-optionen-lernen&f11=0f a one-stop solution for responsive images. The challenge was to create a script that allows you, the developer, to use any combination of the solutions currently being standardized, without bloating it to the point that not using it at all would be more lightweight.

Imagine polyfilling an image that would normally take 2 seconds to load using a JavaScript file that takes 10 seconds to load — it wouldn’t make much sense. Picturefill 2.0 avoids this by following the specification very closely (with some intentional omissions, which we’ll go over in a bit) and letting you use either srcset or picture or a combination of the two.

Picturefill is an responsive image approach that mimics the proposed picture element using divs.
Picturefill is an responsive image approach that mimics the proposed picture element using divs. (Larger version)

While we can’t reliably achieve everything in the specification using JavaScript (such as reasonably detecting bandwidth, which would be a user setting anyway), we can certainly take care of all of the pieces that are meant to be in HTML (i.e. elements and attributes). This version of Picturefill gets us one step closer to not needing Picturefill, which is the ultimate goal of anyone who has ever written a polyfill.

If you’re currently using version 1.0, I highly recommend upgrading to 2.0. It’s a big step towards a better solution to serving the correct image to the user. Some big changes have been made to the syntax and functionality. Let’s look at what’s new.

What’s New in 2.0

One thing that makes this polyfill different from others that I’ve seen is that it polyfills a concept, not just an unsupported block of HTML. Picturefill 1.0 used spans and custom attributes to mimic how we thought responsive images should work. For the record, it is a great solution, and I currently use it for many of my projects that haven’t been converted to 2.0.

In the last year or so, the specification for srcset and picture have matured so much, so we can now actually get to use something close to the real syntax. Picturefill is starting to look like a true polyfill, one we can strip away when real support shows up.

Installing and Using the Polyfill

If you’ve read this far, then you’ve probably dealt with some form of polyfill in the past. This one isn’t much different. Polyfills are supposed to be set-it-and-forget-it (to steal a line from Ronco), but because this is an HTML polyfill, you’ll need either to create the picture element manually or use some form of HTML shiv to do it for you. Luckily, HTML shivs are pretty common and ship with toolkits such as Modernizr; just verify that picture is supported in whatever shiv you choose.

<!-- Create the actual picture element if you haven’t already. -->
<script>
  document.createElement( "picture" );
</script>

<!-- Asynchronously load the polyfill. -->
<script src="picturefill.js" async></script>  

Other than creating the picture element, you simply have to link to the script. Using the async attribute is also recommended, so that Picturefill doesn’t block your page from loading.

Using Picturefill 2.0 With srcset

Let’s look at the syntax that provides the best support and that uses srcset. It should look familiar because it has the same attributes that we saw when discussing the specification.

<img sizes="100vw, (min-width: 40em) 80vw"
srcset="pic-small.png 400w, pic-medium.png 800w, pic-large.png 1200w" alt="Obama">  

The most glaring difference between this snippet and the specification is the absence of a fallback src attribute, which was intentionally removed to prevent images from being downloaded twice in unsupported browsers. And, really, what would be the point of this if images were downloaded twice? Other than that, it’s pretty faithful to the specification, but it will probably evolve over time as the specification fleshes out and the polyfill matures.

The sizes attribute tells the browser of the image’s size relative to the viewport. This often gets overlooked because srcset is the buzzword now, but this attribute is equally important. If you’d like to learn more, Eric Portis makes a lot of sense of this “blimey complicated mess.”

Using Picturefill 2.0 With the picture Element

The RICG did such a good job with this second version of Picturefill that the syntax of the picture element should come as no surprise. It matches the specification very closely:

<picture>
  <source srcset="extralarge.jpg, extralarge.jpg 2x" media="(min-width: 1000px)">
  <source srcset="large.jpg, large.jpg 2x" media="(min-width: 800px)">
  <source srcset="medium.jpg">
  <img srcset="medium.jpg" alt="Cambodia Map">
</picture>  

The biggest change between versions 1.0 and 2.0 is the removal of some traditional HTML (divs and spans) and the addition of newer elements (picture and source). Also, srcset support is built in (heck, why not, right? It’s in the spec!). This is great step forward for this polyfill.

Use as many or as few of these options as you’d like. In line with the specification, if you don’t want to use the 2x option, you don’t have to (and so on). http://caboclonharaue.com/?kreosan=op%C3%A7%C3%B5es-bin%C3%A1rias-robo&7b5=1c The difference between this and the official picture element is the img fallback. You’ll notice here that the img fallback also has a srcset attribute, instead of a normal src (which is widely supported). Again, this is to prevent double-downloading (it’s a real problem). The srcset in the img tag would also cause double-downloading if the browser supports srcset but not picture. This bug should get worked out in the beta version.

Like many good polyfills, Picturefill 2.0 can be executed programmatically by exposing a global function, picturefill(). This allows you to use it in any ultra-hip JavaScript framework that you’d like. You can read about a few options for targeting specific images in the API documentation.

Degrading Gracefully

Earlier in the article, I alluded to the challenge of degrading the img tag gracefully in unsupported browsers. This was another problem in creating Picturefill 2.0. Because it is a polyfill, the concept of unsupported browsers doesn’t really exist (kind of) — we’re using JavaScript to force it to work.

The edge case is this: If a browser doesn’t natively support picture or srcset and has JavaScript turned off, then you’ll get a frowny face. I can already feel your eyes rolling, but knowing the limitations of a system is important before you rely on it on a large scale. If a user were to come across a Picturefill’ed image in an unsupported browser with JavaScript turned off, they would see the image’s alt text — a nice little way to reinforce the importance of descriptive and meaningful alt text, isn’t it?

Alternative text is the fallback because the previous <noscript> solution caused problems with browsers that support picture or srcset but have JavaScript disabled (two images would render). The group also explored adding a src attribute to img (as in the specification), but that results in double-downloading, which defeats the purpose of allocating the appropriate image assets to the user.

We’ve come a long way with responsive images. We can see the light at the end of the tunnel, but a lot of work still has to be done. And we’d love your help!

How To Get Involved

If you’d like to get involved and help out with the responsive-images movement, join the RICG via the W3C. If that’s too much, we’re always looking for people to try out Picturefill’s beta version and submit bugs through the issue tracker on GitHub.

You can also spread the word about great tools like Sizer Soze, which calculates the performance cost of not using responsive images.

Resources and Further Reading

(al, ml)

The post Picturefill 2.0: Responsive Images And The Perfect Polyfill appeared first on Smashing Magazine.

An Introduction to Creating a bbPress Theme From Scratch

As stated in the article preview, bbPress is a plugin that provides forum functionality to WordPress. It is released and maintained by the creators of WordPress, so it is under active development.

In part one of this series, I will be providing an introduction to bbPress, its features, how to install it and configuring it, and then how to create forums and forum categories.

Ultimately, this series seeks to be a guide for anyone who is looking to get started with bbPress both from an installation and configuration perspective, and from the perspective of those who want to develop compatible themes.

What Is bbPress?

There is a lot of forum software that’s already available – phpBB, vBulletin, and so on. bbPress is a forum software that adds forum features to WordPress. It comes as a plugin that you install and activate in your WordPress installation. bbPress is created and maintained by the same people that develop WordPress.

What Are Some of the Features of bbPress?

Before we jump too far into why we’re actually taking a look at bbPress as a viable alternative for forum software, as well as how we can develop compatible themes, let’s take a look at some of the features that make this a viable choice for WordPress:

  • it’s lightweight
  • supports the creation of multiple forums
  • allows the creation of multiple forum categories
  • users can subscribe to individual forums
  • support for many forum converters 
  • abilities to view who started each topic (and in which forum they started it)
  • view the number of people engaged in conversation
  • view the number of replies to the topic
  • and more!

We’ll be covering more throughout the remainder of this series, but that’s a survey of some of the things that we’ll be covering.

Installing and Configuring bbPress

If you have installed and activated a WordPress plugin in the past, then you’ll have no problem downloading and install bbPress. There is no need you install any special software to use bbPress. All you just need is to search for bbPress right from your WordPress admin area under the “Add New” sub-menu located under the “Plugins” menu in your WordPress dashboard.

Once you have installed and activated the plugin, you might need to configure some basic options to get started with using the plugin. This is not a must, but I highly recommend checking out the bbPress settings page located under the “Forums” sub-menu located under the “Settings” menu in your WordPress dashboard.

Here’s the initial bbPress settings screen within the WordPress dashboard:

Visit this settings page to change the basic options that comes with the plugin.

Creating Forum and Forum Categories

To get started with creating our bbPress theme we need to have some basic data with which to work. This includes multiple forums, multiple forum categories, and multiple forum posts.

So let’s go ahead and create some of that data to get started with our work. 

To create a new forum, you need to click the “New Forum” sub-menu located under the “Forums” menu in your WordPress admin area.

Clicking on that option will displaying the following forum:

  • To create a new forum category, you need to select “Category” as the type on the right-hand side of the dashboard.
  • To create a new forum, you need to select “Forum” as the type at the right-hand side of the dashboard.
  • To assign a forum to a category after creating the category, under “Parent” select the category to which you want the forum to be assigned.
  • Other options that are available include “Status” which allows you to choose whether the forum is open or closedm and “Visibility” which allows you to choose whether the forum is public, private or hidden.
  • For a “Public Forum” anyone can see the forum, for a “Hidden Forum” only site Moderators/Admins can see them while “Private Forums” can only be accessed by registered users.

After creating our forum and categories the only thing left is to add posts to these forums.

What’s Next?

Thus far, we’ve introduced bbPress, covered many of its features, how to install and configure it, and how to setup forums and categories.

In the next part of this series, we’ll get out hands dirty with by starting to create our first bbPress theme from scratch.

Efficiently Simplifying Navigation, Part 2: Navigation Systems

How do we make navigation as simple and predictable as possible? As explained in part 1 of this series, the first two steps are to structure content in a way that naturally narrows the navigation options, and to explain those options in a way that minimizes the cognitive load on users.

However, two more steps are required — namely, to choose the right type of navigation menu, and then to design it. The second part of this series addresses the third step and discusses rencontre slovenie which type of navigation menu is best suited to which content.

A navigation menu is any area of an interface that presents navigation options to enable users to find content on the website. This excludes, for example, articles and product pages, which might contain hyperlinks but whose main purpose is consumption, not navigation.

A common distinction in navigation models is between a primary, traditional navigation system and secondary, alternate navigation models. Exactly defining this distinction is difficult. One could say that traditional navigation requires users mainly to click or hover in order to select or browse meta-data categories, while alternate navigation lacks at least one of these aspects.

Traditional Navigation Menus

There are five types of traditional navigation menus or widgets, which can be ordered from simplest to most complex:

  1. Menu bar
  2. Regular drop-down menu
  3. Mega-menu
  4. Separate page
  5. Dynamic filters

While sophisticated hybrid solutions are possible and do exist, all hybrid navigation can be broken down into the five menu types above. The question now, of course, is when to use which type of menu.

As explained in part 1, rencontres crap 2015 designers use three methods to explain navigational choices: text, text and pictures, and text, pictures and descriptions. To minimize the cognitive load on users, designers should use just enough information as the target audience needs to understand their options.

With that in mind, the following rule of thumb will help you decide when to use which type of navigation menu: The fewer the options are and the less information that is necessary to explain them, the simpler the navigation should be.

To better understand why certain widgets are easier to use and when exactly to choose one over the other, let’s take a closer look at the five menu types.

Menu Bar

Almost every website has a persistent horizontal or vertical bar to accommodate its top-level categories.

The first and most basic navigation anchor - a horizontal or vertical bar of links
The first and most basic navigation anchor — a horizontal or vertical bar of links. (Large preview, Image source: top: Sharify, bottom: Arbor Restaurant)

http://secfloripa.org.br/esminer/2004 Recommendation

The most important or most frequently accessed items or categories should go in the navigation bar.

http://mohsen.ir/?danilov= § ® Š § ± § ª- § « § ¦ Š ©- § ¦ ¯- § ª ¯ § Explanation

A navigation bar is the simplest type of navigation. The items or categories in a navigation bar are globally and directly visible and accessible. By contrast, users have to hover over a drop-down menu or wait for a separate page to load in order to access the options they contain.

click here Problems

As soon as the navigation bar (whether horizontal or vertical) takes on more than just a handful of items, and depending on the screen’s width and orientation, it will take up space that could be used more efficiently to present the main content.

In the screenshot below, notice that the horizontal navigation works well, as long as it takes up only a single row. To accommodate it on a smaller screen, the designers chose to stack the navigation items into rows. This, however, pushes the main content down, requiring users to scroll more.

Multiple rows of navigation make it more difficult to access the content.
Multiple rows of navigation make it more difficult to access the content. (Large preview, Image source: Bay Street Biergarten)

On a wide screen, a vertical navigation bar allows for more menu items, but it has another downside. It takes up horizontal space that could be used to more efficiently present the main content on a wide screen, whether an article, a video or product information. In the pictures below, I’ve mocked up a layout to compare the effect.

Vertical navigation can hamper the presentation of content on wide screens.
Vertical navigation can hamper the presentation of content on wide screens. (Large preview, Adapted from: Bay Street Biergarten)

This is why drop-down and fly-out menus are better suited to many items. They present the additional items only when requested but stay out of the way otherwise, thus giving the content center stage.

Regular Drop-Down Menus

A drop-down or fly-out menu, when triggered, appears on top of the content. Its entries are stacked vertically in a single column and consist either of text alone or text and icons.

A drop-down menu vertically stacks its entries in a single column.
A drop-down menu vertically stacks its entries in a single column. (Large preview, Image source: Blurb)

go Recommendation

If the items are best explained by text and the menu is not very long, then a regular drop-down menu is the simplest, most efficient solution.

http://www.romagnamotorsport.it/?binarnewe=quanto-e-il-minimo-di-versamento-per-avere-il-conto-demo-in-opzioni-binarie&469=05 Explanation

Compared to a mega-menu, a regular drop-down menu has the following advantages:

  • It loads more quickly.
  • The additional space and visual potential of a mega-menu would not be taken advantage of with just a few text entries. Also, a mega-menu might confuse users or, at best, slow them down because users would have to figure out the layout scheme first. By contrast, a short vertical list is readily scannable and understood by everyone.

site rencontre pour sportifs Problems

If the menu is long, then things can get tricky. A long vertical drop-down list might get cut off by the browser window and require users to scroll frequently. There are two ways to deal with this problem.

One is to break down the list into subcategories. While a good solution, navigating from submenu to submenu can be frustrating if the interaction is not designed properly. This issue will be addressed in part 3 of this series.

A second way to deal with a long drop-down menu is to use a mega-menu that best fits the screen’s orientation, such as a horizontal mega-menu for landscape-oriented screens.

If screen space is critical, adjusting the menu to the screen’s orientation is a good workaround.
If screen space is critical, adjusting the menu to the screen’s orientation is a good workaround. (Large preview, Image source: Sunglass Hut)

Mega-Menus

A special type of drop-down menu is the so-called mega-menu. A mega-menu is a drop-down or fly-out menu that does not merely stack its entries in a single column, but instead uses images, typographical hierarchy and different layouts to visualize the options.

A mega-menu is a larger, more sophisticated drop-down menu.
A mega-menu is a larger, more sophisticated drop-down menu. (Large preview, Image source: Design Chemical)

Recommendation

If the options require both text and pictures, then a mega-menu is the best choice.

Explanation

A regular drop-down menu does not offer the same room or visualization options. And whether regular and mega, it has the following advantages over navigation on a separate page:

  • It loads more quickly.
  • The cognitive load on users is less. With a separate page, users have to think more. “Which are the ads?” “Which is genuine content?” “Where is the navigation?” A drop-down menu shows only the navigation, and it appears close to the user’s cursor or finger.

Problems

Even a mega-menu is limited in space. If the number of items is too high, then a separate page becomes inevitable.

Separate Pages

A fourth way to display items or categories is on a separate page.

A separate page spaciously accommodates subcategories.
A separate page spaciously accommodates subcategories. (Large preview, Image source: Danske Bank)

Recommendation

If the menu requires text, pictures and descriptions, then a separate page is best.

Explanation

Accommodating this kind of navigation as a mega-menu might be possible, but only if the descriptions are just a couple of lines long.

Problems

Sending users to a separate page merely to view navigation options, rather than actual content, is not the most elegant solution. Also, users are taken out of the context of the current page. But if a mega-menu would be too unwieldy to accommodate the sheer number and size of options, then a separate page might be the most comfortable solution.

Dynamic Filters

Finally, dynamic filters are a complex yet powerful way to navigate content, whereby users assemble a set of their desired content on the fly.

Complex yet powerful, dynamic filters enable users to generate a custom set of content on the fly.
Complex yet powerful, dynamic filters enable users to generate a custom set of content on the fly. (Large preview, Image source: Walmart)

While many websites have only one of the first three menu types, dynamic filters almost never appear on their own. Instead, they are typically appended to the primary navigation as an option.

Kmart (pictured below) starts the navigation process with drop-down menus, both regular and mega. At the next level, a separate page displays the product categories. Finally, once users have navigated to a department, they will find dynamic filters to refine their selection.

Dynamic filters are often appended to traditional navigation.
Dynamic filters are often appended to traditional navigation. (Large preview, Image source: Kmart)

Recommendation

In line with the discussion of meta data categories in part 1, we can say that, while the first three navigation types are best suited to essential and mutually exclusive optional categories, dynamic filters are best employed for optional categories that will likely be combined.

Explanation

The advantage of dynamic filters is that they allow users to select and change values on the fly. Instead of going back and forth between navigation levels, users can stay on the same level and dynamically combine values until the results match their criteria.

The fact that dynamic filters are usually vertical is not a disadvantage because the filtered results are not “content” per se. They are still a part of the navigation. Moreover, the dynamic relationship between the selected values on the left and the results on the right gives the user immediate feedback on how many and which items match their criteria.

Problems

Dynamic filters are the most powerful but also the most complex solution. They take up more space and take longer to load than any other type. Users are required to analyze and work with multiple elements, including filters, results, sorting widgets and viewing modes, which make dynamic filters a challenge to implement on the desktop, let alone on phones. So, as useful as they are, avoid them if a simpler navigation type would do the job just as well.

Alternate Navigation

Almost all websites use one of the traditional types as their main navigation. Many, however, supplement them with alternate navigation systems. Evaluating the most popular ones, therefore, is also important.

Here are the four most common types of alternate navigation:

  • Search
  • Site map
  • A – Z index
  • Tags

Search

Search spares users from having to navigate many levels and gets them directly to their destination. The difference is that the title of the page that contains the desired results will have been set manually by the user.

Search is a shortcut to the desired content in a complex system with multiple levels.
Search is a shortcut to the desired content in a complex system with multiple levels. (Large preview, Image source: The Boston Globe)

The designer would apply a tagging and keyword system to all pages to account for possible miscommunication between the user and search engine, such as typos, synonyms and different conceptual models of the content. In other words, the search engine will try to guess what the user means by their query.

Recommendation

Present search as a supplement to traditional navigation, not as an equal or as the primary means of navigation.

Explanation

Various studies reach different conclusions on whether users are search-dominant. Of course, search-dominance can be influenced by how search is designed and presented, and prior experiences with poorly designed navigation can increase search-dominance. In any case, don’t promote search as the primary method.

Despite these efforts that developers take to avoid mistakes, the success rate of search queries remains low. The reason is that every website typically has its own labels, categorization schemes and naming conventions. Users will typically not know the specifics, so they will often guess-type their query, which can be a cumbersome and vague process, leading many to search just once, maybe twice, before giving up. This is especially true on mobile devices, where typing queries is less comfortable.

Another problem is that, even if all of the results are relevant, users might question whether they are complete. “Did the search engine miss something by misinterpreting my query?” “Did I miss something by not properly phrasing my query?” Traditional navigation, by contrast, defines and presents the categories, as well as shows a comprehensive list of all relevant entries, giving the user certainty as they browse.

A second phenomenon that is often discussed is that search has a higher conversion rate than navigation menus. This, however, can be explained by the distinction between browsing and searching. Users who are browsing will typically use the menu and will be less determined to buy something, whereas users who know the name of what they want to buy will usually just type it into the search field.

Nevertheless, even if search is more efficient for finding particular products than browsing, it is not as popular with users.

Users tend to prefer traditional navigation to search, even when searching for a particular product.
Users tend to prefer traditional navigation to search, even when searching for a particular product. (Large preview, Image source: KISSmetrics blog)

One problem with search is that, with all of the specific and often regionally different product names and model types, recalling a product’s exact name is not straightforward. “Was it GS-50 or G-150?” “Does this one have the extended battery?” With dynamic filters, users may specify exactly the features they are looking for, without having to recall model type or version number.

Another problem is that search can hamper the discovery of related items. If the user finds the exact item they are looking for through search, it might be the only item they see. With dynamic filters, users will see not only the desired item, but also similar items, including ones that have additional features or a lower price.

Adding dynamic filters to a search engine is possible, of course, which would essentially combine the advantages of both navigation models in one interface.

All in all, a search engine, especially one with sophisticated features and algorithms, can produce good results, but its inherent problems keep it inferior to a well-designed traditional menu. This is why search is better as a back-up method, in case the menu fails the user, but not as the primary or sole means of navigation.

Finally, be aware that search works better in native applications populated by user-generated content, because the user will know how they’ve named or tagged their own content.

A – Z Index

An A – Z index comprehensively or almost comprehensively lists the items available on a website, in alphabetical order.

An A - Z index sorts the content of a website comprehensively and alphabetically.
An A – Z index sorts the content of a website comprehensively and alphabetically. (Source: Simply Recipes)

Recommendation

Don’t prioritize an A – Z index over a traditional menu. Also, listing only the category pages is often more efficient than listing thousands of individual pages.

Explanation

An A – Z index is easy to use because everybody knows how to navigate an alphabetical list. But a site-wide index has three problems.

First, an A – Z index typically works well with text but rarely with pictures and descriptions, which are often needed.

Secondly, adjusting vocabulary to the user’s expectations is not straightforward. With regional, outdated or conceptually different terminology, users could wind up looking for an item in a completely wrong section of the index. The only workaround, although one that muddies the information architecture, is to include synonyms. In traditional navigation, synonyms are not as big a problem because, ideally, users will be moving from handful of choices to handful of choices.

Thirdly, an A – Z index, much like search, can hamper the discovery of related items. If users are looking for “eggs and beans” in an A – Z index, they will get eggs and beans and nothing else. In traditional navigation, users would see other breakfast recipes along the way as they navigate to “eggs and beans” through the “Breakfast” category, and without being slowed down (as long as the “Breakfast” category is sorted alphabetically). This is good for both the user and the website.

Site Maps

A site map displays the navigational structure of a website, typically with headings and subheadings.

A site map visualizes the navigational structure of a website.
A site map visualizes the navigational structure of a website. (Large preview, Source: NBCNews.com)

Recommendation

A crawlable sitemap.xml file will help search engines index the website. But its interactive representation, the site map, should be deemphasized as a means of navigation.

Explanation

A site map usually consists only of text. But users often need icons, photographs and descriptions to understand the options. While including these elements in a site map is possible, it would only aggravate the second problem, which is that a site map typically displays all items at once, offering no way to skip or hide undesired items. This poses problems for the user who is trying to scan and interact with the information, especially if the content is voluminous.

Tags

Tags, in their default state, can be described as keywords without parent or child categories. They tend to appear at the end of articles.

14-tags
Tags with a “More about” label (Source: Euronews)

Recommendation

A tag-based system calls for additional measures to work well. But even then, it remains inferior to a traditional category-based system.

Explanation

Of all of the alternate navigation models, tags come closest to traditional navigation. After all, tagging (which is essentially the process of creating meta data) is the first step to building a proper information architecture, the foundation of traditional navigation. However, with even just a handful of tags per article, you could amass hundreds or thousands of tags very quickly.

This is why categorizing the tags is important. By organizing tags into parent and child categories, designers can structure a lot of tags into small sets of related information. Traditional navigation that includes these categories will enable the user to easily skip undesired sets and browse only the ones that interest them.

Many content-based websites, though, substitute a sophisticated traditional menu with hybrid navigation. They categorize tags loosely at best, relying initially on other navigation models, such as internal and external search engines, feeds and social media links. This type of system can get users to the desired article, but it makes it difficult for users to identify the aspect of the article that they’re interested in. To compensate, some designers simply conclude articles with a list of keywords — for example, “Barack Obama,” “Democrats,” “Republicans,” “health care,” “shutdown.” Users would, then, access the tag they are interested in to browse related articles.

In traditional navigation, the user would navigate categories that contain and contextualize the keywords that they are interested in — for example, NewsPoliticsUSDomestic policyHealth care. In this case, the user would be interested in the given article because it discusses the US health care system, not necessarily because it mentions Barack Obama, the Democrats, the Republicans or the shutdown. To see related articles, users would simply access the parent category.

A traditional levels-based menu is the most precise type of navigation.
A traditional levels-based menu is the most precise type of navigation. (Large preview, Image source: The Telegraph)

A tag-based system is most efficient if it is complemented by strong social media and a robust search engine. But it remains a fuzzier way to navigate, more like fishing than purposeful searching. Also, users should not have to rely on search and external links to navigate a website. Instead, they should be able to find any piece of information right from the home page, and a well-designed traditional menu is still the most efficient method to enable that.

Conclusion

When it comes to choosing the right type of navigation, the bottom line is simple: The fewer the options are and the less information that is necessary to explain them, the simpler the navigation should be.

The more difficult question is usually whether and how to implement alternate navigation models, in addition to the traditional system.

Alternate solutions might not be expensive to create or difficult to implement. But they all have inherent obstacles to interaction that prevent them from being viable as primary or exclusive systems. Moreover, users typically do not look for these alternatives unless the main navigation fails them.

So, rather than investing much effort into developing or improving these secondary solutions, invest in properly designing the main navigation, thus hopefully rendering a secondary solution unnecessary.

The recommendations in this article are summarized below.

Choosing Traditional Navigation

  • A vertical navigation bar is no less usable than a horizontal one, but it could draw attention away from the main content by appearing in the same field of view. A horizontal bar is efficient for top-level categories, as long as the items fit on a single row. If a single row is not feasible, then use a drop-down menu or a separate page, rather than a fixed vertical menu.
  • If text is sufficient to explain the options, then go with a regular drop-down menu. Break down long lists into subcategories, or choose a mega-menu layout that suits the screen’s orientation.
  • If text and pictures are required, then go with a mega-menu.
  • If text, pictures and descriptions are necessary, then go with a separate page.
  • The solutions above work well for essential and mutually exclusive optional categories. If optional categories are likely to be combined, then append dynamic filters to the traditional menu.

Choosing Alternate Navigation

  • Search or an A – Z index works well if the user knows the exact name of the item they are looking for. However, both systems are prone to vagueness and often hamper the discoverability of related items. Don’t emphasize them over traditional navigation.
  • Tag-based navigation could be a good alternate system, if properly subcategorizing the content would be too expensive or too difficult. However, it would have to be complemented by strong social media integration and search.

Knowing which navigation type best suits the options counts for a lot. But a fourth step is still required — namely, to design the navigation to be as simple, predictable and comfortable as possible. We’ll discuss this in part 3.

Further Reading

(al, ml, il)

The post Efficiently Simplifying Navigation, Part 2: Navigation Systems appeared first on Smashing Magazine.

Building a Recent Post Widget Powered by SimplePie

In this tutorial, I will introduce SimplePie, build a widget plugin that displays recently published articles queried from the WordPress feed using SimplePie, and discuss the performance advantage of querying posts from the WordPress feed instead of the database.

Introduction to SimplePie

SimplePie is a free, very fast and easy-to-use feed parser, written in PHP that handles all of the dirty work when it comes to fetching, caching, parsing, normalizing data structures between formats, handling character encoding translation, and sanitizing the resulting data.

Getting Started With SimplePie

To install and get started using SimplePie, check out the following steps:

  1. Download SimplePie library and create two folders: php and cache.
  2. Upload library/ and autoloader.php to the php folder you just created.
  3. SimplePie is now installed and ready to be use.

Let’s see how to use SimplePie to retrieve content found in a feed.

<?php
// Make sure SimplePie is included. You may need to change this to match
// the location of autoloader.php

require_once ('../autoloader.php');

// instantiate the SimplePie class
$feed = new SimplePie();

// Set the feed to process.
$feed->set_feed_url( 'http://feeds.fedburner.com/tech4sky' );

// Run SimplePie.
$feed->init();

// Send content to the browser as text/html and the UTF-8 character set.
$feed->handle_content_type();
?>
<!DOCTYPE html>
<head>
	<title>Sample SimplePie Page</title>
</head>
<body>

<div class="header">
  <h1><a href="<?php echo $feed->get_permalink(); ?>"><?php echo $feed->get_title(); ?></a></h1>
  <p><?php echo $feed->get_description(); ?></p>
</div>

<?php
// Here, we'll loop through all of the items in the feed, and $item represents the current item in the loop.
foreach ( $feed->get_items() as $item ):
?>

  <div class="item">
    <h2><a href="<?php echo $item->get_permalink(); ?>"><?php echo $item->get_title(); ?></a></h2>
    <p><?php echo $item->get_description(); ?></p>
    <p><small>Posted on <?php echo $item->get_date('j F Y | g:i a'); ?></small></p>
  </div><!-- .item -->

<?php endforeach; ?>

SimplePie is easy to install and use, isn’t it?

In the next section, we will be building a widget that display recently publish articles retrieved from WordPress feed.

Performance Advantage of Querying Post From Feed Over Database

Many of us use a widget to display Recent Posts on the sidebar of our WordPress blog. Many of these plugins query the database to retrieve the recently published articles.

Considering the fact that database-driven web application like WordPress take time querying and writing to the database, it’s fair to say that the fewer the number of database queries, the more the greater improvement we can see on our page load time.

Rather than querying the database, we could retrieve the recently published articles from our WordPress feed using SimplePie which can significantly improve performance.

SimplePie has several options for caching feed data built-in so you don’t have to pull the entire feed every time.

One of such is the file-based caching system that store cache feed item in a server-writable directory which further maximize performance.

Building a Recent Post Widget With SimplePie

Building a Widget in WordPress is easy and straight-forward.

First, extend the WP_Widget class, include these four methods: __construct(), widget(), form(), update() in the class and finally register the widget.

Recent Post Widget powered by SimplePie
  1. Create a class extending the WP_Widget
    class Tutsplus_simplepie extends WP_Widget {}
  2. Give the widget a name and description via the __construct() magic method
    function __construct() {
    	parent::__construct(
    		'tutsplus_widget', // Base ID
    		__('Recent Post powered by SimplePie', 'text_domain'), // Name
    		array( 'description' => __( 'Most recent posts generated from WordPress feed using SimplePie', 'text_domain' ), )
    	);
    }
  3. The widget() method displays the front-end of the widget.
    public function widget( $args, $instance ) {
    
    	$feedURL = empty( $instance['feedURL'] ) ? site_url() . '/feed' : $instance['feedURL'];
        $feedNumber = empty( $instance['feedNumber'] ) ? 5 : $instance['feedNumber'];
    	$showDate = empty( $instance['showDate'] ) ? 0 : 1;
        $showDescription = empty( $instance['showDescription'] ) ? 0 : 1;
    
    	echo $args['before_widget'];
    
    	$title = apply_filters( 'widget_title', $instance['title'] );
    	if ( ! empty( $title ) ) {
    		echo $args['before_title'] . $title . $args['after_title'];</pre>
    </li>
    <li>
        <pre>require_once 'php/autoloader.php';
    
        // Instantiate and process this feed with all of the default options.
        $feed = new SimplePie();
    
        // Set which feed to process.
        $feed->set_feed_url( $feedURL );
    
        // Set where the cache files should be stored
        $feed->set_cache_location( plugin_dir_path( __FILE__ ) . 'cache' );
    
        // Run SimplePie.
        $feed->init();
    
        // ensure that the content is sent to the browser as text/html and the UTF-8 character set
        $feed->handle_content_type();
    
        // Figure out how many total items there are, but limit it to 5.
        $maxitems = $feed->get_item_quantity( $feedNumber );
    
        // Build an array of all the items, starting with element 0 (first element).
        $rss_items = $feed->get_items( 0, $maxitems );
    
    ?>
    
    <ul>
    	<?php if ( $maxitems == 0 ) : ?>
    	<li>
    		<?php echo "No item found"; ?></li>
    	<?php else : ?>
    		<?php // Loop through each feed item and display each item as a hyperlink. ?>
    		<?php foreach ( $rss_items as $item ) : ?>
    	        <li>
    		        <a href="<?php echo esc_url($item -> get_permalink()); ?>" title="<?php echo esc_html( $item -> get_title() ); ?>">
                        <?php echo esc_html( $item -> get_title() ); ?>
                    </a>
    		        <?php if ( $showDate ) { echo "<span class='date'>" . $item -> get_date('F j Y') . "</span>"; } ?>
    		        <?php if ( $showDescription ) { echo "<div class='description'>" . $item -> get_description() . "</div>"; } ?>
    	        </li>
    	    <?php endforeach; ?>
    	<?php endif; ?>
    </ul>
    
    <?php echo $args['after_widget'];
    }
  4. Create the widget settings form with the form() method
    public function form( $instance ) {
    
    	$defaults = array('title' => 'Recent Posts',
    	    'feedURL' => get_site_url() .'/feed',
    	    'feedNumber' => 5
    	);
    	$instance = wp_parse_args( (array)$instance, $defaults );
    	$title = $instance['title'];
    	$feedURL = $instance['feedURL'];
    	$feedNumber = $instance['feedNumber'];
    	$showDate = $instance['showDate'];
    	$showDescription = $instance['showDescription'];
    ?>
    <p>
    	<label for="<?php echo $this->get_field_id('title'); ?>">Title:</label>
    	<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
    </p>
    <p>
        <label for="<?php echo $this->get_field_id('feedURL'); ?>">Feed:</label>
        <input class="widefat" id="<?php echo $this->get_field_id('feedURL'); ?>" name="<?php echo $thi->get_field_name( 'feedURL' ); ?>" type="text" value="<?php echo esc_attr( $feedURL ); ?>">
    </p>
    <p>
        <label for="<?php echo $this->get_field_id( 'feedNumber' ); ?>">Number of posts to show:</label>
        <input id="<?php echo $this->get_field_id( 'feedNumber' ); ?>" name="<?php echo $this->get_field_name( 'feedNumber' ); ?>" size="3" type="text" value="<?php echo esc_attr( $feedNumber ); ?>">
    </p>
    <p>
        <label for="<?php echo $this->get_field_id( 'showDate' ); ?>">Show Date?:</label>
        <input name="<?php echo $this->get_field_name( 'showDate' ); ?>" value="1" type="checkbox" <?php checked( $showDate, 1 ); ?>">
    </p>
    <p>
        <label for="<?php echo $this->get_field_id('showDescription'); ?>">Show Summary?:</label>
        <input name="<?php echo $this->get_field_name('showDescription'); ?>" value="1" type="checkbox" <?php checked( $showDescription, 1 ); ?>">
    </p>
    <?php
    }
  5. Finally the update() method sanitizes and saved the widget settings to the database.
    public function update( $new_instance, $old_instance ) {
        
        $instance = array();
        $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
        $instance['feedURL'] = ( ! empty( $new_instance['feedURL'] ) ) ? strip_tags( $new_instance['feedURL'] ) : '';
        $instance['feedNumber'] = ( ! empty( $new_instance['feedNumber'] ) ) ? strip_tags( $new_instance['feedNumber'] ) : '';
        $instance['showDate'] = ( ! empty( $new_instance['showDate'] ) ) ? strip_tags( $new_instance['showDate'] ) : '';
        $instance['showDescription'] = ( ! empty( $new_instance['showDescription'] ) ) ? strip_tags( $new_instance['showDescription'] ) : '';
    
        return $instance;
        
    }

The WordPress fetch feed function also retrieves feed and parses it using SimplePie. If you wish to use the fetch feed function instead of implementing SimplePie from ground up, change the widget() method inside the Tutsplus_simplepie Widget class to the code below.

public function widget( $args, $instance ) {

  $feedURL = empty( $instance['feedURL'] ) ? site_url().'/feed' : $instance['feedURL'];
  $feedNumber = (int) empty( $instance['feedNumber'] ) ? 5 : $instance['feedNumber'];
  $showDate = empty( $instance['showDate'] ) ? 0 : 1;
  $showDescription = empty( $instance['showDescription'] ) ? 0 : 1;

  echo $args['before_widget'];

    $title = apply_filters( 'widget_title', $instance['title'] );
    if ( ! empty( $title ) )
        echo $args['before_title'] . $title . $args['after_title'];

    include_once( ABSPATH . WPINC . '/feed.php' );

    // Get a SimplePie feed object from the specified feed source.
    $rss = fetch_feed( $feedURL );

    if ( ! is_wp_error( $rss ) ) : // Checks that the object is created correctly

        // Figure out how many total items there are, but limit it to 5.
        $maxitems = $rss->get_item_quantity( $feedNumber );

        // Build an array of all the items, starting with element 0 (first element).
        $rss_items = $rss->get_items( 0, $maxitems );

    endif;
?>

<ul>
 <?php if ( $maxitems == 0 ) : ?>
    <li><?php echo "No item found"; ?></li>
 <?php else : ?>
    <?php // Loop through each feed item and display each item as a hyperlink. ?>
    <?php foreach ( $rss_items as $item ) : ?>
        <li>
            <a href="<?php echo esc_url($item -> get_permalink()); ?>" title="<?php echo esc_html($item->get_title()); ?>">
                <?php echo esc_html($item->get_title()); ?>
            </a>
            <?php if ($showDate) { echo "<span class='date'>" . $item->get_date('F j Y') . "</span>"; } ?>
            <?php if ($showDescription) { echo "<div class='description'>" . $item->get_description() . "</div>"; } ?>
        </li>
    <?php endforeach; ?>
  <?php endif; ?>
</ul>

<?php echo $args['after_widget'];
}
?>

Note on the Widget

The appearance of the widget will vary from theme to theme based on your stylesheet. Some of us host our feed on FeedBurner so I added a feed URI option field in the widget settings form incase you want to change it with the default feed set to http://yoursite.com/feed.

Other widget options include altering the number “Recent Post” to display , show / hide post summary and date for each post.

Recent Post widget setings form

Conclusion

We are done building the recent post widget. To further understand how the widget was built and how to implement it on your WordPress site, download the tutorial file.

When extracted, the file contains two plugin files in zip:

  1. The first is the widget built using SimplePie.
  2. The other built using WordPress fetch feed function which coincidentally also uses the SimplePie library.

Hopefully this helps with working with building widgets and SimplePie in the future. 

Let me know your thoughts in the comments!

Proper WordPress Filesystem Permissions And Ownerships

When people talk about WordPress security, file permissions and ownership are usually the last thing on their minds. Installing security plugins is a good practice and a must for every WordPress website. However, if your file-system permissions aren’t set up correctly, most of your security measures could be easily bypassed by intruders.

Permissions and ownership are quite important in WordPress installations. Setting these up properly on your Web server should be the first thing you do after installing WordPress. Having the wrong set of permissions could cause fatal errors that stop your website dead. Wrong permissions can also compromise your website and make it prone to attacks.

Aside from the security concerns, a number of other issues can stem from having the wrong set of permissions and ownership. Have you ever encountered a blank white screen when trying to load your website for the first time? Or have you ever received error messages when trying to upload images in the media uploader? Correcting permissions and ownership of your files and folders will often fix these types of problems.

In this article, we will teach you all about WordPress filesystem permissions and ownership: what they are, why they are important and how to set them up. You will learn a few basic principles that I follow to keep my file system intact. We will also cover the two most common WordPress server configurations. We’ll explain how they differ and, more importantly, how to set the proper permissions and ownership for each.

Terminal Vs. FTP Client

During the course of this article, we will be using the terminal to change permissions and ownership. Why not use an FTP client instead? The reason is that FTP is a bit limited for our needs. FTP can be used to transfer files and change file and folder permissions, but it cannot be used to change ownership settings.

To perform the commands listed in this article, you will have to be logged into your server using the SSH command. If you are not familiar with the terminal and SSH, you can learn about them in the article “Introduction to Linux Commands.”

Users And Groups

Before anything else, we need to quickly talk about what users and groups are, because these go hand in hand when defining permissions.

To put it simply, a user is an account that has access to the computer, and a group just is an identifier for a certain set of users. This means that every time you transfer files using FTP, you are using a user account on your server. And depending on how your host has set up your account, you (the user) might belong to one or more groups. Users and groups are like users and roles in WordPress. Both are conceptually the same, except that the former is used on your server.

Users and groups are important because they help to identify privileges for all of our files and folders. Owners of a file normally would have full privileges on it; other users who belong to the same group would have fewer privileges on it; while everyone else might have no privileges on it. These privileges are what we call permissions.

What Are File Permissions?

Permissions dictate what users can do with a file. A permission is represented by a set of numbers, such as 644 or 777, referred to as a permission mode. If you have used plugins in WordPress before, then you’ve most likely been asked by some of them to change the permissions of a file or directory because the plugin can’t write to it. By changing the file’s permissions, you are allowing the Web server to gain access to that file or folder.

Think of a permission mode as a set of “who can do what” statements, in which each digit corresponds to the “who” part of the statement:

  • First digit
    What the user of the account that owns the file can do
  • Second digit
    What other user accounts in the owner’s group can do
  • Third digit
    What the user accounts of everyone else (including website visitors) can do

Next, the number corresponds to the “what” part of the statement and is a sum of a combination of any these digits:

  • 4
    Read a file, or read the names of the files in a folder
  • 2
    Write or modify a file, or modify the contents of a folder
  • 1
    Execute or run a file, or access the files in a folder

These digits are the privileges that are assigned to the “who” in the permission mode. Note in the list above that privileges mean something different for files and folders.

Using the correct permission mode is quite important. To better illustrate this, think again of users and roles in WordPress. On a WordPress website, contributors and administrators have different sets of capabilities. Contributors may create new blog posts, but they may not add plugins. Administrators, on the other hand, may add plugins and also create blog posts. Administrators may even change the look of the website if they want to. A clear line separates what users in different roles can do. This is the same with permission modes, except that instead of dealing with blog posts and theme options, we are dealing with files and folders on the server.

Changing Permission Modes

FTP clients usually provide an interface where you can conveniently change the permission mode of your files and folders. Here’s a screenshot of the interface in my FTP client:

Example of a permission mode interface.
Example of a permission mode interface.

If you have access to your server’s terminal, you can also use the chmod command to change the permission mode of a file or folder:

sudo chmod 644 <file>

To change the permission modes of all files or folders, use chmod in tandem with the find command. For example, you can use this to change all files to 644:

sudo find . -type f -exec chmod 644 {} +

Or use this to change all of your folders to 755:

sudo find . -type d -exec chmod 755 {} +

Refer to “Changing File Permissions in the WordPress Codex” for a guide to changing permission modes.

The Difference Between 644 And 777

Let’s look at some permission modes and how they affect our website.

What would a PHP script with a permission mode of 644 mean? Following the explanation above of how permission modes work, we can decipher what this mode allows users to do with our script:

  • The owner’s privileges are “read” (4) + “write” (2) = 6
  • The owner’s group privileges are “read” (4) = 4
  • Everyone else’s privileges are “read” (4) = 4

In plain language, this means that:

  • if we own the script, we may read and modify it;
  • everyone else may only read it.

As we can see, 644 is a good permission mode for our PHP script. We can make changes to it, and our Web server can read it.

Now let’s look at folders. What if we owned a folder that had a permission mode of 777? This permission mode can be broken down as follows:

  • The owner’s privileges are “read” (4) + “write” (2) + “execute” (1) = 7
  • The owner’s group privileges are “read” (4) + “write” (2) + “execute” (1) = 7
  • Everyone else’s privileges are “read” (4) + “write” (2) + “execute” (1) = 7

This means that

  • anyone may get a list of file names in our folder;
  • anyone may create, modify and delete any file in our folder;
  • anyone may access the files in our folder.

It is obvious that 777 is a bad permission mode for anything on our WordPress website because any visitor would be able to add files to our directory or even delete scripts. Worse, anyone would be able to put in malicious code and compromise our website.

WordPress Server Configurations

Now we know about permissions and how to read them. But before proceeding to change all of our permissions, we need to understand how our server is set up. Because permissions deal with user accounts and groups, we need to know how our WordPress website runs.

A lot of different server configurations are out there. Different configurations need different sets of permission modes for WordPress to work correctly and securely. We’ll talk about just the two most common configurations and the proper permissions for them:

  • Standard server configuration:
    • You have a user account.
    • Your Web server runs as another user account.
  • Shared server configuration or suEXEC configuration:
    • You have a user account.
    • Other people who use the server have user accounts and might share the same group with your user account.
    • Your Web server runs as the owner of your WordPress files.

The main difference between these two is in how the Web server runs.

Permissions For A Standard WordPress Server Configuration

Standard WordPress configurations require a bit more work than shared server configurations because the Web server has no relationship to our user account.

File and Folder Ownership for WordPress

First, we need to adjust the file and folder ownerships of our WordPress files. We’ll have to make sure of the following:

  • that your user account is the owner of all WordPress files and folders,
  • that your user account and the Web server’s user account belong to the same group.

To find out the groups that your user account belongs to, you can use this command in your server’s terminal:

groups

Then, to find out the groups that your Web server belongs to, you can temporarily insert this PHP snippet in one of your WordPress scripts:

echo exec( 'groups' );

If your user and the Web server don’t belong to the same group, you can use the following command in the terminal to add your user to one of your Web server’s groups:

sudo usermod -a -G <a-common-group-name> myuser

Lastly, to ensure that everything in our WordPress folder belongs to our user account and has the shared group that we just added, perform this command in your WordPress folder:

sudo find . -exec chown myuser:a-common-group-name {} +

Permissions for WordPress

All of our files and folders should now have the correct ownership. Now it’s time to adjust the permission modes. To make things simpler, you’ll only need to remember the following:

  • All files should be 664.
  • All folders should be 775.
  • wp-config.php should be 660.

Here’s what we’re trying to achieve with this set of permission modes:

  • Our user account may read and modify our files.
  • WordPress (via our Web server) may read and modify our scripts.
  • WordPress may create, modify or delete files and folders.
  • Other people may not see our database credentials in wp-config.php.

You might be thinking that allowing WordPress full privileges with our folders is not secure. Don’t worry — we’re doing this because WordPress needs certain features to create and modify files. WordPress allows us to upload and remove themes and plugins and even edit scripts and styles from the administrative back end. Without this type of permission, we would have to manually upload themes and plugins every time using FTP.

You can use your FTP client to change the permission modes, or you can use the following commands in your WordPress directory to quickly adjust the permissions of all of your files and folders:

sudo find . -type f -exec chmod 664 {} +
sudo find . -type d -exec chmod 775 {} +
sudo chmod 660 wp-config.php

Note that some Web servers are stricter than others. If yours is strict, then setting your wp-config.php to 660 might stop your website from working. In this case, just leave it as 664.

Permissions For A Shared Server Configuration Or SuEXEC Configuration

Permissions for shared server configurations are easier to implement. We won’t dwell on ownership because the Web server runs as the owner of our files and folders. Because our user account and the Web server share the same permissions (both are owners), we can dive right into modifying the permission modes:

  • All files should be 644.
  • All folders should be 755.
  • wp-config.php should be 600.

Similar to the previous set of permission modes, these break down as follows:

  • Our user account may read and modify our files.
  • WordPress (via our Web server and as the account owner) may read and modify our scripts.
  • WordPress may create, modify or delete files or folders.
  • Other people may not see our database credentials in wp-config.php.

Again, you can use an FTP client to change the permission modes, or you can use the following commands in your WordPress directory to quickly adjust the permissions of all of your files and folders:

sudo find . -type f -exec chmod 644 {} +
sudo find . -type d -exec chmod 755 {} +
sudo chmod 600 wp-config.php

Similar to the standard WordPress server configuration, your server might be stricter than others and might not allow wp-config.php to be 600. In this case, you can adjust it to a more lenient 640; if that still doesn’t work, then use 644.

Always follow these guidelines and your WordPress files should be kept safe from intruders.

Common Pitfalls

A common mistake people make is to set the uploads folder to 777. Some do this because they get an error when trying to upload an image to their website, and 777 quickly fixes this problem. But never give unlimited access to everyone, or else you’ll make the Web server vulnerable to attack. If you follow the guidelines covered in this article, then you should have no problems uploading files to your website.

At times, though, a plugin will request that you set a file to 777. On these occasions, you can temporarily set it to 777, but make sure to set it back to its original permission mode when you’re done.

Conclusion

We’ve learned now about the proper permissions and file ownership of a WordPress website. We’ve also learned to avoid a permission mode of 777 because of how it endangers the Web server.

Hopefully, you can implement these tips to keep your WordPress website safe and secure. If you have any additional tips regarding permissions and security, please share them in the comments below.

Excerpt image credit: Christopher Ross

(al, ml)

The post Proper WordPress Filesystem Permissions And Ownerships appeared first on Smashing Magazine.

Archives

Categories