Server Side Mustard Cut

The term “mustard cutting” in web design comes from developers at the BBC who wanted to serve different experiences of their site to different browsers on different devices. They were specifically trying to avoid User Agent sniffing:

But these days, with such a long tail of user agents now accessing the site, this becomes a fruitless exercise.

Instead, they used feature detection. Modernizr is the classic (awesome) example of that, but ala carte feature tests can be quite small and simple all by themselves. This is the logic the BBC used to determine if a browser cut the mustard or not:

if('querySelector' in document      && 'localStorage' in window      && 'addEventListener' in window) {      // bootstrap the javascript application      }

If that logic failed, the website still loads what they called a core experience. If that logic passed, additional resources would load for an enhanced experience.

Pretty cool.

Loading additional CSS and JavaScript is fairly easy

There are various ways to do it, typically involving an XHR for the resource. Filament Group has some very tiny, focused scripts just for this: loadCSS and loadJS.

Loading a bit of extra HTML via XHR is similarly easy. But…

It’s too hard to load an entirely different document client-side

Say you don’t need just a bit of extra CSS, scripts, or a bit of HTML. What you want is an entirely different document.

Your “core experience” and “enhanced experience” are entirely different sets of HTML, CSS, and JavaScript. Trying to do this client-side would mean trying to load a super bare-bones document, then trying to essentially re-create how the browser parser works. First you mustard-cut, then XHR for the right set of HTML you need, then either drop it into the DOM, or perhaps wait until you’ve XHR’d for the CSS so you don’t get a flash of unstyled document. Then XHR for all the scripts, and make sure that you execute them in order (tricky).

Hard to pull off.

Allow the server to serve the correct document based on mustard-cutting information

If the server knew the results of your mustard-cut, you could avoid all that trouble and serve the correct document right off the bat.

That’s the whole point of client-side mustard-cutting: it can only be done on the client. But… you could save that data to a cookie, and cookies can be read by the server.

It you had a cookie you could count on, you could do something like this in the routing of your site:

<?php   // This is just a fake routing/controller kinda setup.   if (isset($  _COOKIE["mustard"])) {     // Enhanced experience     if ($  _COOKIE["mustard"] == true) {       include_once("enhanced.php");     // Core experience     } else {       include_once("core.php");     }   // No cookie = core experience   } else {     include_once("core.php");   } ?>

What happens on the first page view though?

That’s the tricky part here. That cookie won’t exist on the first page view. You could just let subsequent pages serve the correct experience, but that’s not likely to be acceptable.

Here comes the most controversial part: if you don’t have the cookie but can tell the browser supports them and they are enabled, you refresh the page.

Refresh the page?! Are you kidding?

Totally reasonable questions: How can a refresh possibly be a good user experience? Aren’t refreshes slow? Couldn’t you get caught in a refresh loop?

I think all of these things can be addressed.

At the very top of the document, if that cookie is not there and the browser does support cookies:

  1. Mustard-cut and save the data to a cookie with JavaScript
  2. If the mustard-cut data tells you you should be loading a different document: halt the page from loading/doing anything else (window.stop();) and refresh (location.reload(true);).

Upon refresh, the cookie will be there for the server.

It all happens so fast when it’s the very first thing a document does that I find it barely noticeable. This is what we’re doing for the editor page on CodePen, see:

Fresh page load on a new incognito window (no cookies saved). The desktop view is actually the default, but the refresh happens and the mobile view loads because of a mustard-cut.

The trick to avoiding a refresh loop is to only execute that part of the JavaScript if you’re sure cookies are supported and enabled.

The mustard-cutting script

Here’s a mustard-cut that only tests the screen width. Bear in mind a mustard-cut could be anything you want it to be that you can test client-side.

(function() {    // If the browser supports cookies and they are enabled   if (navigator.cookieEnabled) {      // Set the cookie for 3 days     var date = new Date();     date.setTime(date.getTime() + (3 * 24 * 60 * 60 * 1000));     var expires = "; expires=" + date.toGMTString();      // This is where we're setting the mustard cutting information.     // In this case we're just setting screen width, but it could     // be anything. Think http://modernizr.com/     document.cookie = "screen-width=" + window.outerWidth + expires + "; path=/";      /*       Only refresh if the WRONG template loads.        Since we're defaulting to a small screen,       and we know if this script is running the       cookie wasn't present on this page load,       we should refresh if the screen is wider       than 700.        This needs to be kept in sync with the server       side distinction     */     if (window.outerWidth > 700) {        // Halt the browser from loading/doing anything else.       window.stop();        // Reload the page, because the cookie will now be       // set and the server can use it.       location.reload(true);      }    }  }());

In fact, we don’t have to load that script at all if the cookie is already there, since if it is, we know the correct page has loaded already.

<?php     // Run this script as high up the page as you can,     // but only if the cookie isn't already present.     if (isset($  _COOKIE["screen-width"]) == 0) { ?>       <script src="mobile-mustard.js"></script> <?php } ?>

Possible Scenarios

  • The normal first time visitor: No cookie is present. Mustard-cut script will run and refresh the page quickly. They will get correct document based on cut.
  • The repeat visitor: Cookie is already present. They will get correct document based on cut.
  • Visitor with incorrect cookie: Perhaps they have a desktop browser but it was very narrow when the page loaded the first time, but they have since widened it. We can detect that with a CSS @media query and offer a link to correct the problem (see demo).
  • Visitor with cookies off: We serve our choice of documents. Could potentially be wrong. Serve the best likely case based on data.
  • Visitor in which JavaScript doesn’t run: We serve our choice of documents. Could potentially be wrong. Serve the best likely case based on data.

Possible Problems

For the record, I’m not saying this is the best possible solution to this problem. In fact, if you’re in a situation where you can do everything purely client-side, that’s probably better.

Here’s some potential problems with this solution:

  • Perhaps the reload is slower than I think it is. I didn’t do any testing of super old / super slow devices like I probably should have.
  • HTML caching could be a problem. I experienced this first hand when building the demo on a site that was using that method. The server serves a cached document, which then is determined to be the incorrect one and refreshed, causing the dreaded refresh loop. Solution: don’t HTML cache this page, or redirect to subdomains based on the cut.
  • Security settings that prevent server-side access to cookies created by JavaScript. If you can’t control that, that would be a problem.

I do use this technique in production though and haven’t had an issue in a lot of months, so I’m pretty happy with it.

Demo and Repo

Here’s a demo and the code is up on GitHub if you spot any fouls.

Also, I thought client hints was supposed to be the savior here, but I’m just not sure anymore where it fits into this situation.


Server Side Mustard Cut is a post from CSS-Tricks

CSS-Tricks

FacebookTwitterGoogle+LinkedInEmailPinterest

WordPress Functionality Plugins

The following is a guest post by Jason Witt. I’ve known for quite a while that I should port a lot of the stuff from my `functions.php` in my WordPress theme into a functionality plugin. But you know, hours in the day and all that. I recently had Jason work on this project for me, and he did a bang up job. If you have no idea what I’m talking about, read on.

Adding new functionality to a WordPress site can be as easy as searching for a plugin in the WordPress Plugin Repository and installing that plugin. But there is some custom functionality you might need that is either too basic or too customized for there to be a plugin for it. That’s where the `functions.php` file comes in. It’s essentially a functionality dumping grounds for a theme.

But some of the code we tend to put there would be better served elsewhere.

The `functions.php` file is an easy place to add things like theme support options, custom post types, enqueue JavaScript, and (really) anything else you can think of. For years this has been the de facto way of adding custom functionality to you WordPress theme. In the past couple of years there’s has been a movement of taking the functionality you’d normally put in the `functions.php` file moving it out into a “functionality plugin”.

What is a Functionality Plugin?

A functionality plugin is just a plugin like any other plugin you’d find in the WordPress Plugin Repository. The main difference is that it wouldn’t be publicly distributed, because it’s specific to your site. It’s one custom plugin that encompasses all your site’s custom functionality.

What’s So Great About a Functionality Plugin?

Why would you want to spend the time building a plugin when putting your functionality in your `functions.php` file is so easy? The big advantage is that you can reuse your functionality from theme to theme. When updating/changing your theme, some code in the `functions.php` will stay the same and some will change. The idea behind a functionality plugin is to take the functionality that will not change from theme to theme, and place it into a plugin. That way instead of sorting through your `functions.php` file for what you want to keep, you can just dive into the design of your new theme.

What Goes Into the Plugin?

This is the million dollar question. What does actually go into a functionality plugin? The best way to approach this is to decide what is specific to the theme and what is specific to the site. For instance, a custom post type would be specific to a site, and adding thumbnail support is specific to a theme.

Let’s pause on that for a moment so it can be super clear.

Imagine your website has a section for meetups on it. You’ve built a custom post type for them, so they can be a special type of content. On the front end of the site, you display them in a special way. On the back end of the site, you collect special information specific to meetups. Like in this CSS-Tricks video. We’ll call that Theme A.

If you change the theme of your site (Theme B), is it likely you’ll want your meetups to go away? Probably not. That is site content that you’ll likely want to transcend any particular theme.

If you had declared all that custom post types stuff (e.g. register_post_type())in your `functions.php` file of Theme A, then switched to Theme Byou might suffer a minor heart attack when you notice that all your meetups information is gone. Theme A’s `functions.php` file is no longer active, so all that code declaring the custom post type no longer runs. The menus are not added to the admin, the content will appear to be gone.

Rest assured, the data is still there, you just need to make sure the custom post types code runs again.

Why go through that at all? Just move that code into a functionality plugin and it will remain active even when switching themes.

Now imagine something different entirely: code in your `functions.php` file that enqueues a JavaScript library. You’re probably using that library do things on the front end of your site. That’s pretty specific to the theme. Another theme might use different libraries entirely, or none at all. That kind of thing makes sense to be in the `functions.php` file as it’s specific to the theme, not the content.

Examples of things that make sense in `functions.php`

  • The theme support functions e.g. add_theme_support('post-thumbnails');
  • JavaScript related to the front end
  • Adding a custom post type to your home page post list
  • Registering sidebars and nav menus
  • Adding an external CSS file, for instance a custom font

Examples of things that make sense in a functionality plugin:

  • Custom post types
  • Custom Taxonomies
  • Custom functionality for other plugins
  • Custom meta fields
  • Mostly custom stuff

Getting Started

If you’ve never make a WordPress plugin before, this is a great way to gain some experience.

To start, you’ll make a directory in you plugins directory. Name it whatever you want. Avoid using numbers and special characters; dashes and underscores are OK. I usually go with something mysitename-functionality.

In you new plugin folder create a file with a similar name as the folder, mysitename-functionality.php.

At the top of that file you want to ad the plugin file header information. Here’s an example to get you started.

/**  * Plugin Name:       Your Functionality Plugin Name  * Plugin URI:        http://example.com/plugin-name-uri/  * Description:       This is a short description of what the plugin does. It's displayed in the WordPress admin area.  * Version:           1.0.0  * Author:            Your Name or Your Company  * Author URI:        http://example.com/  * License:           GPL-2.0+  * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt  * Text Domain:       plugin-name  * Domain Path:       /languages  */

After that, go nuts and start adding your functionality below.

You can literally just cut-and-paste code from `functions.php` over to this file, and as long as this plugin is activated, it should work.

Modular Design

If you’re like me and like to keep things neat and tidy, this is a great time to use a modular approach to the code you place in your plugin.

One approach to keep things simple is to organize your functionality into similar groups and give each of them their own file. Then, include those files into the main file of the plugin using PHP includes. Make sure you notate your functions so when you return to them at a later date you know what’s going on.

include 'mysitename-functionality-post-types.php'; include 'mysitename-functionality-extra-rss-feeds.php'; include 'mysitename-functionality-remove-unwanted-assets.php';

Another approach is to use Object Oriented Programing (OOP). This involves creating PHP classes and methods. If you are not familiar with Object Oriented Programing there’s a great tutorial by Tom McFarlin called Object-Oriented Programming in WordPress. You should check it out if you’re interested in developing your WordPress coding skills. OOP is a great way to organize your code that’ll allow it grow as your functionality needs change.

Real Example

If you’d like to poke around the CSS-Tricks functionality plugin, here’s a repo on GitHub you can check out.

After this transition here, the only thing left in the `functions.php` file is queuing up jQuery and a hook that overrides the default HTML comment output – both things very specific to the current theme.


WordPress Functionality Plugins is a post from CSS-Tricks

CSS-Tricks

FacebookTwitterGoogle+LinkedInEmailPinterest

Win an Annual Subscription: PixelKit Premium UI Kits and Design Resources

Let’s start the week off with some freebies, shall we?

We’re running a giveaway courtesy of the folks at PixelKit, who are generously sharing three annual membership subscriptions with our readers.

PixelKit is stocked with thousands of graphics perfect for any web designer. All UI kits are 100% specialized, which means they will include everything you need for app screens, navigation controls, and more. Just look at what is available and you will find a variety of different sliders, buttons, icons, just to name a few.

Here’s a preview of some of the icon sets and UI kits available:

Swanky Outlines Icon Set

This vector outline set is perfect for a flat or metro website and even works for apps.

Outlines Icon Set

Modern Touch UI Kit

If you need to guarantee your website will be functional and stylish, then this is the flat UI kit for you. With a nice typography balance between weight and positioning and the perfect paddings, colors, and margins, this kit will give a distinctive edge to any website.

Flat UI Kit

Charming Boutique Icon Set

This icon set is ideal for an eCommerce website or any type of online store. Thirty icons are modern, flat, and ideal for shopping and call-to-action needs.

Shopping Icons

Fashion Ave UI Kit UI Kit

When you need a UI kit for an eCommerce or shopping website, you cannot go wrong with this one. It includes a wide variety of elements designed with fashion shopping in mind. It offers just the right feel to separate your website designs from the competition.

eCommerce UI Kit

Gentle Edges Icon Set

When you need a minimalist icon set, then look no further. Offering more than 1000 icons fully vectorized, this 46 category set is sure to fit your commercial projects.

Minimalist Icon Set

Metro Vibes UI Kit

The metro look and feel to this UI kit will certainly turn heads when you use it on your mordern styled website or application.

Metro UI Kit

Take a look at this neat treat – the Free PixelKit Bootstrap UI Kits. These modern HTML templates can be used to make your design cool looking, functional, and professional.

The PixelKit Giveaway

Get the chance to win one of the three annual full subscriptions to PixelKit by following the directions in the Rafflecopter widget below.

a Rafflecopter giveaway

If you win, the high-quality UI kits will be available immediately to you and that means you can get done with your next project more quickly than you ever imagined.

So, happy tweeting, commenting, and sharing!

Important note: The giveaway starts today (March 30) and ends on Friday (April 3). The winners will be announced on Monday (April 6).

The post Win an Annual Subscription: PixelKit Premium UI Kits and Design Resources appeared first on SpyreStudios.


SpyreStudios

FacebookTwitterGoogle+LinkedInEmailPinterest

How to Create a Mega Menu for Your WordPress Website

Mega Menu is an effective menu solution for any WordPress website which needs complicated and content-rich menu navigation, especially eCommerce websites. Fortunately, we can use a plugin to create a mega menu for your website.

Using WR Mega Menu

Below, I will guide you through creating a mega menu by using a free WordPress plugin: WR Mega Menu in only 3 simple steps:

Step 1: Install WR Mega Menu

Install

Like other plugins’ installation progress, you can go to Plugins -> Add New -> Upload plugin, then upload the zip file from Woorockets.com or search for WR Mega Menu in the Search plugins box, install it to your WordPress website and then activate the plugin. When the installation is successful, you are welcomed by this interface:

Interface

Step 2: Create A Default WordPress Menu

Notes:

The menu will display in your homepage. Make sure you create your menu structure to neatly fit your website and keep it easy to navigate since the menu will be the guide for your website’s visitors.

This step is compulsory since the WR Mega menu plugin only allows you to customize pre-made menus created in the WordPress menu.

In the WordPress Admin panel, go to Appearance -> Menus and start editing your menu here.

Appearance - Menus

This menu will be automatically assigned to WR Mega Menu. You can build up more than one menu and easily switch among them.

WR Mega Menu also allows you to choose from those menus to customize.

In the Menus tab, type your menu name in the Menu name box and press Create Menu. If you have more than one menu, this step will save you time in browsing the one you need.

Create Menu

After creating a menu, in the Menu Structure options, you can add unlimited menu items from the left column. In the screenshot below, I have WooCommerce installed with some pre-created pages like My Account, Checkout, Cart…

Pages

Similarly, you can also add Categories or Links to your menu.

In the Links box, you can add menu items with URL links to specific a location within your website.

Type your menu item name in the box then click Add to Menu.

Add Links

Menu Settings controls how your menu will appear in the front-end. The menu’s positions will depend on the theme you’re using for your website.

In this case, as I use the Twenty Fourteen theme so I have Top primary menu and Secondary menu in the left side bar to select from.

Select Menu Position

With simple drag and drop, you can easily create submenu items and arrange them in the way you want.

Add Submenu Items

You can also select an icon for each menu item and sub menu item from nearly 150 icons available.

The selected icon here will display in WR Mega Menu when you select button Icon Only or Icon vs Text.

Add Icon

When editing is done, remember to click Save Menu before moving to the next step.

Step 3: Create Mega Menu with WR Mega Menu

Go to WR Mega Menu -> Add new then type your menu title in the box. You can also go to WR Mega Menu and then click Add new button in the top of the page:

Add New Profile

Then click ‘Turn on’ WR Mega Menu to start customization.

After turning on WR Mega Menu, the editing fields will appear like this:

Editing Fields

Edit row and column:

Edit Row and Column

WR Mega Menu allows you to add unlimited rows and a maximum of 12 columns for each row. You also can control the size of each column and row by drag-and-drop action.

There are several pre-designed columns in the WR Mega Menu with specific ratios to choose from.

However, always remember to keep your menu simple and easy for your website visitors.

Add elements:
Note: WR Mega Menu provides Standard elements and Widget elements. These 2 types of elements have the similar editing progress.

In this tutorial, I will guide you through how to manage with Standard elements and you can apply the same steps with Widget elements to build your own mega menu.

You can add built-in elements for both rows and columns.

Add Image element:

In the Content tab:

Upload your image to Image elements and then adjust Alt Text, Caption and link type of image on On Click option.

You can preview your image in the Preview window right next to it.

Image Settings Content

In the Appearance tab:

You can edit your image with several options: Container style, Alignment, customize Margin or add Fade in Animations.

Image Settings Appearance

If you know about coding, you can overwrite custom CSS class and ID to get what you want in the Advanced option:

Advanced

Add Text element:

You can easily edit text in the WordPress editor in the Content tab.

Content

In the Appearance tab, you can set Margin, enable Dropcap, adjust line height for the text and customize CSS in the Advanced option.

WP Appearance

For example, I customized image and text for Home item in mega menu and this is how it displays in the front-end:

Customization Example

Add Submenu element:

Note: You can only add Submenu to pre-made menus which contain sub items.

In the Content tab:

You can add all submenus or select several ones to customize in the Appearance tab.

Submenu Content

With the same process with other 2 elements above, the Appearance tab in Submenu allows you to adjust Column breaking or customize CSS in the Advanced option.

Submenu Appearance

In addition, by clicking the Styling button on top of the WR Mega Menu editing field, you can easily set customization for Menu bar and Submenu Panel. You can set an icon and text in the Menu Bar tab and adjust the Submenu Panel as you desire. You can also adjust images or text to make your submenus more lively and beautiful. Everything is under your control:

Styling

For example, Shop mega menu contains 3 submenus: Lookbook, For She and For He along with text and images.

Submenus Example

Wrapping Up

I hope this tutorial is useful for you to build your own mega menu easily. If you need any further help while configuring your Mega Menu, feel free to ask in the comments section below. You are always welcome.


Onextrapixel – Web Design and Development Online Magazine

FacebookTwitterGoogle+LinkedInEmailPinterest

Introduction to WordPress Front End Security: Escaping the Things

If you’re a WordPress developer that writes HTML/CSS/JS (which is 100% of theme developers and 99% of plugin developers), you need to know the basics of front end security for WordPress. WordPress gives you all the tools you need to make your theme or plugin secure. You just need to know how and when to use each tool.

For example, one huge responsibility you have as a front-end developer is to prevent unescaped content from being printed to the page.

Security Is Your Responsibility

Before we talk specifics, I’d like to squash an idea that I would (previously) use to rationalize a “less strict” view of front end security:

“If a hacker is already able to change the code/database/content, what difference does it make if my front-end code is secure? Couldn’t they already do more substantial damage?”

Yes, if a hacker already has control of the code or database, chances are they don’t care how well-secured the output is (they can probably change it anyway).

Even so, you still have a responsibility to make the front-end code secure. A few reasons why:

  • Proper front end security also prevents user error from causing big problems. If the user accidentally puts a special character in a field they weren’t supposed to, the page won’t explode.
  • Some attacks are limited. Perhaps the hacker had minimal control and could only change a single piece of content in the database. You can prevent that narrow attack from becoming much larger.
  • Security is an onion. The outermost (often inedible) layer is the front-end display. Good security practices make it that tiny bit harder for a hacker to exploit a site.

Enough with the pep talk. Let’s talk about securing our WordPress themes and plugins.

What Are We Worried About?

A major concern for a front end developer is avoiding Cross-Site Scripting (XSS for short, because ‘CSS’ would cause all sorts of problems. Puns and one-liners welcome.).

XSS vulnerabilities allow bad people (“hackers”) to steal information. Typically that means stealing cookies and session information. If a bad person can send your active session back to themselves (hence the “cross site” part), they could use that to be logged in to your account and do anything you could do (bad news bears).

What is Escaping?

In computer science the word “escape” has a special meaning:

To convert a character or string of characters to be interpreted literally within a specific context, typically to prevent those characters from being interpreted as code.

Put another way, in the context of WordPress front-end development: Escaping changes possibly evil content into safe content.

The biggest danger here is generally <script> tags and other methods of executing JavaScript (e.g. onclick="javascript:"). If a <script> can be output on the page an executed, that’s super dangerous. Escaping means turning that into &lt;script&gt; which is safe.

Why You Need To Escape: An Example

In case you’re not familiar with XSS, a quick example will demonstrate the risk.

Suppose your theme had a field to add a link for further reading. A “Read More” link, if you will. On the WordPress dashboard, it might look like this:

Custom Field

In your theme, you’d like to display this link at the bottom of the post, like so:

Custom Field on the Front End

So, you open up single.php (the file responsible for displaying blog posts) and add the following near the bottom:

<?php    $  read_more_link = get_post_meta(      get_the_ID(),      'read_more_link',      true    );  ?>  <!-- Don't do this --> <a href="<?php echo $  read_more_link; ?>">Read More</a>

Suppose someone maliciously enters this text into your custom field:

Custom Field With Evil Script

When you visit the page, here’s what you’ll see:

Evil Script Executed!

Yikes! If that bad input allowed a bad person to execute JavaScript, they could:

  • Redirect the user
  • Hijack the user’s cookies
  • Do other bad things

An Escape for Everything

Now that we know how important escaping is, let’s look at the escaping methods WordPress provides and give some context for each.

Function: esc_html

Used for: Output that should have absolutely no HTML in the output.

What it does: Converts HTML special characters (such as <, >, &) into their “escaped” entity (&lt;, &gt;, &amp;).

A common example would be displaying text-only custom fields in a theme:

<?php $  dog_name = get_post_meta( $  post_id, 'dog_name', true ); ?> <span class="dog-name"><?php echo esc_html( $  dog_name ); ?></span>

Codex entry for esc_html

Function: esc_attr

Used for: Output being used in the context of an HTML attribute (think “title”, “data-” fields, “alt” text).

What it does: The exact same thing as esc_html. The only difference is that different WordPress filters are applied to each function.

Here’s esc_attr used on an image:

<img src="/images/duck.png"  alt="<?php echo esc_attr( $  alt_text ); ?>"  title="<?php echo esc_attr( $  title ); ?>" >

Codex entry for esc_attr

Function: esc_url

Used for: Output that is necessarily a URL. Examples would be image src attributes and href values.

What it does: A more thorough, specific escaping than the esc_attr & esc_html functions, which removes or converts any characters not allowed in URLs into their URL-safe format.

Use esc_url when you need to output a link or dynamic image path:

<a href="<?php echo esc_url( $  url ); ?>">Link Text</a> <img src="<?php echo esc_url( $  image_url ); ?>" >

Codex entry for esc_url

Function: esc_js

Used for: Printing JavaScript strings, primarily on inline attributes like onclick.

What it does: Converts special characters like <, >, quotes – anything that could break JavaScript code.

esc_js is probably the least used of the esc_ functions, for a few reasons:

  1. Most JS is loaded in a separate file.
  2. Most JS isn’t written inline as attributes.
  3. For non-inline JS, json_encode is a better option.

But, if you ever need to escape some inline JS, here’s how you’d do it:

<?php $  message = get_post_meta( get_the_ID(), 'onclick_message', true ); ?> <a href="/blog/" onclick="alert('<?php echo esc_js( $  message ); ?>')">...</a>

Codex entry for esc_js

Function: json_encode

Used for: Printing a PHP variable for use in JavaScript.

What it does: Converts a PHP variable (object, string, array, whatever) into a sensible, escaped JavaScript representation of that PHP variable.

Useful in particular for <script> blocks making use of WP variables. A simple example:

<?php $  categories = get_categories(); ?> <script type="text/javascript"> 	var allCategories = <?php echo json_encode( $  categories ); ?>; 	// Do something interesting with categories here </script>

PHP reference for json_encode

Function: wp_kses

Used for: Output that needs to allow some HTML, but not all tags or attributes.

What it does: Strips the content of any tags or attributes that don’t match the list of rules passed in.

Use wp_kses if there is a context that allows certain tags (e.g. inline formatting tags like <strong> and <em>) to be printed as HTML.

A basic example would be displaying comments:

<div class="comment-text">   <?php              echo wp_kses(        $  comment_text,        // Only allow <a>, <strong>, and <em> tags       array(         'a' => array(           // Here, we whitelist 'href' and 'title' attributes - nothing else allowed!           'href' => array(),           'title' => array()         ),         'br' => array(),         'em' => array(),         'strong' => array()        )     );   ?> </div>

Codex entry for wp_kses

What are the _e and _x versions of the escaping functions (esc_attr_e, esc_attr_x)?

These are convenience functions (to make your life easier), and they’re useful when printing translatable strings: text that can be changed with a WordPress translation file.

If you’re developing a theme or plugin for wide distribution (vs. a one-use client project), you’ll want to make every string internationalization-friendly. That means PHP strings that were once under your control become editable by translators – hence the need for escaping (you can’t trust anybody):

<a href="/blog/" title="<?php esc_attr_e( 'Go To Blog', 'my_theme' ); ?>">Blog</a>

The second parameter to the _e functions is the translation domain. It is used by translators when they write and generate their translations.

The _x functions (like esc_html_x) are essentially the same as their _e counterparts, with an added “context” argument to explain the context a word or phrase is used in. Useful for words with multiple meanings:

<!-- Here, we're asking the user to comment (verb): --> <a href="#comment">   <?php      echo esc_html_x(        'Comment',        'Verb: To leave a comment', // Here's the contextual help       'my_theme'      );    ?> </a> <!-- Here, we're simply adding a heading with the text "Comment" (noun) --> <h3>   <?php      echo esc_html_x(        'Comment',        'Noun: An individual comment', // Here's the contextual help       'my_theme'      );    ?> </h3>

Codex entry for esc_attr_e
Codex entry for esc_attr_x

What about the_title and the_content?

If you crack open the default WordPress theme (named “Twenty Fifteen” at the time of this writing), you’ll see code like this outputting the title of a post:

<header class="entry-header">     <?php the_title( '<h1 class="entry-title">', '</h1>' ); ?> </header><!-- .entry-header -->

You’ll also see unescaped calls to the_content like so:

<?php the_content(); ?>

You may be panicking. Why aren’t those functions escaped?! 2 reasons:

1. WordPress automatically escapes them

Functions like the_title are convenience functions – tools that make front-end development easier. As such, to make it even easier for developers, WordPress already automatically escapes the output for the_title.

2. Context: Some Content is HTML

In the case of the_content, the output is expected to be unescaped HTML. When the user adds a <div> to their content, we can assume they actually want a <div> output to the page – instead of the escaped version.

If you have security concerns with a user being able to add scripts to the_content‘s output, you can use wp_kses to strip unwanted tags from the final output. This would be useful on subdomains and shared hosting, and I’m pretty sure this is what they use on WordPress.com (a hosted version of WordPress where users aren’t allowed to add their own JavaScript).

Handy tip: If you want to use the_title as an HTML attribute, use the_title_attibute to save yourself an escape. the_title_attribute in action:

<span title="<?php the_title_attribute(); ?>">...</span>

Escape the Things

I work with a lot of plugins and themes – commercial, free, and custom-built – and I see lots of unescaped content (and resulting XSS vulnerabilities). Hopefully, this article will equip you with the basic tools you need to make your WordPress things safer.

Did I overlook anything? Let me know in the comments!


Introduction to WordPress Front End Security: Escaping the Things is a post from CSS-Tricks

CSS-Tricks

FacebookTwitterGoogle+LinkedInEmailPinterest

WordPress Front End Security: CSRF and Nonces

In our last article, we covered Cross-Site Scripting (XSS) and the functions WordPress provides to prevent XSS attacks. Today, we’ll look at another security concern for front end developers: Cross-Site Request Forgery (CSRF).

Lest you think this security stuff isn’t important, a major vulnerability was recently found in the WP SEO plugin, which is installed on 1,000,000+ WordPress sites and which allowed hackers to manipulate the WordPress database using CSRF. (The plugin was fixed quickly, but you can see how scary this stuff can be.)

Nonces and Cross-Site Request Forgery

Put simply, CSRF is when bad guys try to trick users (usually someone with access to the WordPress dashboard) into doing something they didn’t intend to do. A simple example can help illustrate:

Suppose you were building a WordPress plugin to allow logged-in users to submit their pictures. On the front end of the site, your plugin might generate a form like so:

<?php if ( is_user_logged_in() ) : ?>   <form action="/submit-picture/" method="get">     <input type="text" name="picture_url">     <input type="submit">   </form> <?php endif; ?>

On the back end, you handle the picture form submissions:

if ( is_user_logged_in() && isset( $  _REQUEST['picture_url'] ) ) {   // Save the picture here }

Now, suppose a hacker wants to submit a fake picture. The hacker doesn’t have a username or password – so they can’t do anything, right?

Not quite. To hijack one of your users’ accounts to submit a fake picture, the hacker could try to get a logged-in user to click a link that looks like this:

http://your-site.com/submit-picture/?picture_url=fake-picture.jpg

If a logged-in user clicks that link, what would stop the picture from being submitted? You guessed it: Nothing. Hacker wins.

That’s because we didn’t do anything to verify the user’s intention to submit a picture. The “F” in CSRF stands for forgery: The hacker has forged (faked) a request on behalf of the user, kind of like how you forged your mom’s signature on sick notes in elementary school.

How to Prevent CSRF

We can stop CSRF attacks by using some handy functionality built into WordPress. To prevent a request from being successfully “forged”, WordPress uses nonces (numbers used once) to validate the request was actually made by the current user.

The basic process looks like this:

  1. A nonce is generated.
  2. That nonce is submitted with the form.
  3. On the back end, the nonce is checked for validity. If valid, the action continues. If invalid, everything halts – the request was probably forged!

Let’s Add a Nonce

On the front end, suppose we wanted to add a nonce to a form submission. We’ll do this with the wp_nonce_field convenience function:

<form action="/submit-picture/" method="get">   <input type="text" name="picture_url">   <input type="submit">   <?php wp_nonce_field( 'submit_picture' ); ?> </form>

Easy, right? Now, when we’re processing this form on the back end, we just need to use some built-in WordPress functions to verify that the nonce was valid:

// By default, we can find the nonce in the "_wpnonce" request parameter. $  nonce = $  _REQUEST['_wpnonce']; if ( ! wp_verify_nonce( $  nonce, 'submit_picture' ) ) {   exit; // Get out of here, the nonce is rotten! }  // Now we can process the submission if ( is_user_logged_in() && isset( $  _REQUEST['picture_url'] ) ) {   // Save the picture here }

Because the nonce is unknown to the hacker, he can’t craft a fake link that will do harm. Any malicious attempts will be squashed at the wp_verify_nonce check. We’ve stopped the hacker, right?! For many cases, yes. We’ve made it much more difficult for a hacker to forge a request.

Nonces are User-Specific

But what if a bad logged-in user of your site wanted to submit a fake picture for another user? Couldn’t the bad user could just look at the HTML source of the site, find the nonce field, and add it to their “evil” URL like so?

http://your-site.com/submit-picture/?picture_url=fake-picture.jpg&_wpnonce=NONCEVALUE

Fortunately, it won’t work. WordPress nonces are unique to a user’s session, so a hacker couldn’t substitute his own nonce for another user.

Hat tip to Mark Allen in the comments for pointing out session-unique nonces.

Try These Nonce Functions

WordPress is full of convenience functions to make generating nonces (and preventing CSRF) easier. Here are a few you might find useful for different situations:

Function: wp_verify_nonce

What it does: Validates that the nonce value was legitimately generated by WordPress.

No matter how you generate your nonce, it should be checked on the back end with wp_verify_nonce

Just like the examples above, use wp_verify_nonce to verify a user’s intent:

$  submitted_value = $  _REQUEST['_wpnonce'];  if ( wp_verify_nonce( $  submitted_value, 'your_action_name' ) ) {   // nonce was valid... }

Codex entry for wp_verify_nonce

Function: wp_nonce_field

What it does: Prints a hidden <input> tag containing a nonce value.

Used when you’re building a <form> that needs to be protected from CSRF (which is pretty much every <form>).

Just like in the examples above, wp_nonce_field is a convenience function to make our life easier building HTML forms:

<form> <!-- Other form fields go here --> <?php wp_nonce_field( 'your_action_name' ); ?> </form>

Codex entry for wp_nonce_field

Function: wp_nonce_url

What it does: Returns a URL with a nonce value attached.

Used when you’re building a URL that needs a nonce field appended as a query string parameter. Most useful when doing GET requests that need CSRF validation.

Here’s an example of wp_nonce_url where we need to validate that a user intended to click a link:

<?php   $  action_url = wp_nonce_url( '/change-color/?color=blue', 'change_color' );   // $  action_url is now "/change-color/?color=blue&_wpnonce=GENERATED_VALUE" ?> <a href="<?php echo esc_url( $  action_url ); ?>">Change to blue</a>

Codex entry for wp_nonce_url

Function: wp_create_nonce

What it does: Generates a nonce value.

Used when you need a nonce value that doesn’t fit one of the above convenience functions.

Here’s wp_create_nonce used to generate a nonce value for returning in JSON format (useful for returning in AJAX requests):

<?php   $  nonce_value = wp_create_nonce( 'your_action_name' );    return json_encode( array( 'nonce' => $  nonce_value ) ); ?>

Codex entry for wp_create_nonce

Function: check_ajax_referer

What it does: Checks for a submitted nonce using wp_verify_nonce, and if the validation fails, stops execution.

check_ajax_referer is another convenience function mainly for use in AJAX requests. You can use it to skip doing the wp_verify_nonce check yourself:

<?php   // Forged requests won't get past this line:   check_ajax_referer( 'your_action_name' );    // Do your action here ?>

Codex entry for check_ajax_referer

Nonces for Everything!

CSRF vulnerabilities range from harmless (e.g. poll submissions) to extremely dangerous (e.g. modifying passwords or permissions).

Regardless of severity, you should be using nonces to prevent CSRF any time a user does an action in WordPress. Because…why wouldn’t you? You don’t want hackers forging requests on your site, and WordPress gives you the tools to stop them.

Use nonces, stop forgery, and foil hackers!


WordPress Front End Security: CSRF and Nonces is a post from CSS-Tricks

CSS-Tricks

FacebookTwitterGoogle+LinkedInEmailPinterest

Vintage is Back in Trend: Best Retro Website Designs

Fashion for retro and vintage style has gradually moved from podiums and fashion shows to website design. It has been actively used in a variety of contexts: in advertising, corporate design, blog design, etc. Moreover, nowadays you can even find webdesign studios that specialize in vintage designing only.

Retro Website Design

There are several old-fashioned graphic elements that are used in design to recreate a retro atmosphere:

  • Texture: torn paper, ink texture, old printing paper
  • Text: old-style typography, script fonts and handwriting
  • Illustrations: images from old posters, old photos, pin-up girls images
  • Images of old objects: radio and TV devices, cars

This article presents a collection of 10 best websites designed in vintage and retro styles. Perhaps the following examples will inspire you to create new, exciting projects on the Internet.

Mom & Popcorn

Mom & Popcorn

Tommy

Tommy

Essaymama

Essaymama

Lord Likely

Lord Likely

Literary Bohemian

Literary Bohemian

Team Fannypack

Team Fannypack

Cottonseed Oil Tour

Cottonseed Oil Tour

Sprocket House

Sprocket House

Targetscope

Target-Scope

Prahba

Prahba

Conclusion

Clients may think that retro web design can be used only for corporate styles of popular and stylish old time places like retro cafes, restaurants, barbershops or cinemas. However the collection above has just proved the opposite as vintage website design can be suitable for a variety of companies from different industries.

Obviously retro style can never get outdated as it doesn’t only evoke nostalgia, but is proven to be exceptionally moderate, laconic and attractive.

So what do you think, have designers succeeded in reviving the past on the modern web?


Onextrapixel – Web Design and Development Online Magazine

FacebookTwitterGoogle+LinkedInEmailPinterest

Get In Touch!

Or save my details for later...