The Deal with WordPress Transients

Go to Source

The following is a guest post by Scott Fennell. In this article Scott is going to dig into an important type of caching that is available to you in WordPress: transients. Like any cache, you use transients to store any kind of data that takes a long time to get, so the next time you need it, it returns super fast. The beauty of transients is they clean up after themselves, as long as you watch out for the pitfalls Scott describes here!

The web has gotten really “API-ish”. By that I mean, almost every major site is pushing and pulling content to and from other sites. Consider:

  • A near-majority of ESPN.com seems to actually be Twitter.
  • Programmable Web is now tracking over 13,000 API’s.
  • One of the biggest initiatives around WordPress for many months has been the WP-API.

In my own work, I’ve seen client and employer expectations grow to include the hope — nay, the assumption — that my skill set includes API integration. It’s not enough to paste in an email signup form as an <iframe>. Rather, my agency needs them abstracted into a [shortcode] for easier maintenance. It’s not sufficient to paste in a product slider via some 3rd party JavaScript, rather the designer expects precise control of the animations. Having a developer log in to a CDN to see if a domain is in development mode is too time-consuming, so we call the CDN and display the status in the dashboard.

WordPress provides with us with some phenomenal tools for API integrations. One of these is the Transients API. It’s one of my favorite things that ship with WordPress, and I’d like to share a few tricks with you. If you are new to transients in general, read on. If you already get the concept and want to skip to the nuts and bolts, feel free to do so.

One more thing: I’m going to assume you are familiar with making HTTP requests from a WordPress plugin, as it would be beyond the scope of this article to lay that out in detail. My examples will all use the WordPress HTTP API for making requests.

What do transients have to do with API integrations?

Any time you are calling a remote server, there’s some extra latency, sometimes a quite a bit of extra latency. Transients allow you to cache the response that you get from the remote API, storing it nearby in your WordPress database (well, usually in the database; more on that later). Also, many API’s have a rate-limit, meaning you are only allowed to make x amount of requests within a given time period. Transients allow you to request that API response from yourself, saving you many, many remote calls.

What are transients, exactly?

They’re a way to cache information. Transients are a form of caching that takes place on the server, as opposed to browser caching. Think of a transient as an organism that has three components:

  1. A key. A short string of text. The name of the organism.
  2. A value. Any php variable. The body — the guts, if you will — of the organism.
  3. A lifespan. Often expressed as a time constant such as DAY_IN_SECONDS. The amount of time for which we want this organism to live.

Transients are very similar to WordPress options, only transients have a designated lifespan. Because of that, they are an excellent choice for storing the result of remote calls.

Huh… So what if the remote API changes its response? And won’t all these transients clutter up my database?

That’s the cool thing about transients: They expire automatically. If you attempt to retrieve a transient from your database after it has expired, WordPress will automatically delete it, preventing any clutter. At the same time, it will re-create it anew, ensuring that you have (reasonably) fresh content from the remote API.

Whoa, wait, WordPress will delete my valuable information?

Yeah, it will. Transients are absolutely not for storing data that can’t be automatically re-created. Therefore, you wouldn’t use a transient to store, for example, data that a user is entering in a form on your site.

Are transients just for remote calls?

Transients are for any chunk of information that takes a long time to generate. They will improve server latency for any routine more complex than retrieving a single database cell. That said, they are more code, and more code means more bugs. Therefore, I tend to reserve them for either remote calls or really large queries.

How does this work exactly?

Let’s say you want a list of recent subscribers to your email newsletter. You use a third party service for email updates, and it exposes your list of subscribers via an API. Here’s the sequence:

  1. Right now, you’d have to call the API to ask it for the list of subscribers, since you don’t have that information handy.
  2. The API responds to your request with the list of subscribers, and although it takes a few hundred milliseconds, you get the API response you need.
  3. You store that data on your server, in a transient, giving it a lifespan of HOUR_IN_SECONDS, meaning one hour.
  4. For the next hour, every time a user loads your list of recent subscribers, it’ll happen really quickly, since it’s all stored in one big pile, in one cell in your database.
  5. An hour goes by and a user tries to load your page. WordPress notices that the lifespan has expired, it deletes your local value, and you’re back to step one of this process.

I still don’t get it.

The WROX book on plugin development has a fantastic chapter on transients, as does the codex.

Okay, I get it. Snippet me.

Here’s what transients look like in their most basic form:

<?php
/**
 * Get a list of email subscribers.
 *
 * @return object The HTTP response that comes as a result of a wp_remote_get().
 */
function css_t_subscribers() {

  // Do we have this information in our transients already?
  $transient = get_transient( 'css_t_subscribers' );
  
  // Yep!  Just return it and we're done.
  if( ! empty( $transient ) ) {
    
    // The function will return here every time after the first time it is run, until the transient expires.
    return $transient;

  // Nope!  We gotta make a call.
  } else {
  
    // We got this url from the documentation for the remote API.
    $url = 'https://api.example.com/v4/subscribers';
    
    // We are structuring these args based on the API docs as well.
    $args = array(
      'headers' => array(
        'token' => 'example_token'
      ),
    );
    
    // Call the API.
    $out = wp_remote_get( $url, $args );
    
    // Save the API response so we don't have to call again until tomorrow.
    set_transient( 'css_t_subscribers', $out, DAY_IN_SECONDS );
    
    // Return the list of subscribers.  The function will return here the first time it is run, and then once again, each time the transient expires.
    return $out;
    
  }
  
}
?>

That’s the basic routine: Check for the value locally, if you have it great, if not, grab it remotely and store it locally for next time.

But I was promised tricks.

Yes! I have some tricks to share now that you’ve seen the basics. I’m not going to bundle this up into a final example, because your treatment will likely need be tailored to your application. This is a grab bag, and I’m going to organize it around the three components of a transient that I explained earlier:

  1. The name.
  2. The content.
  3. The lifespan.

Intriguing: These are also the three values that get passed to set_transient().

Tricks for naming your transient

This is by far the deepest part of my grab bag of tricks when it comes to transients. It’s a little counter-intuitive, but naming your transients is the hardest thing about using them. The way you name your transients can open up a number of powerful opportunities, or break your plugin altogether.

Prefixing your transient names

It’s helpful to be able to identify all of the transients that pertain to your plugin. The way to do this is to prefix them with your plugin namespace. This is also crucial for preventing collisions with other transients. That’s why you see me doing `css_t_subscribers` instead of just `subscribers` in most of my examples here, where `css_t` is my imaginary prefix for css-tricks.com.

Changing the name in order to break the cache

There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors. — Phil Karlton, via Martin Fowler

Amazing! Out of the three hard problems in computer science, naming your transient involves two of them: Naming things, and cache invalidation. Naming your transient relates to cache invalidation because if you change the name of your transient, then WordPress won’t be able to find it. This can be actually be a good thing, because it forces your plugin to call the remote API to get fresh data.

An occasion for this might be when you release a new version of the plugin. It stands to reason that if the plugin code has changed, then you would want your code to grab refreshed transients instead of continuing to serve the old ones that assume the old plugin code. One way to do this is to include the version number of your plugin in your transient name:

<?php

  // This is the version number for our plugin.
  CSS_T_VERSION = '3.1.4';

  function css_t_subscribers() {

    // Do we have this information in our transients already?
    $transient = get_transient( 'css_t_subscribers' . CSS_T_VERSION );
  
    // Do things...
    
    // Save the API response so we don't have to call again until tomorrow.
    set_transient( 'css_t_subscribers' . CSS_T_VERSION, $out, DAY_IN_SECONDS );
    
  }
  
?>

I like to use a constant because constants are global, so I don’t have to pass it into my function — it’s already there. However, I make sure to prefix the constant itself, it in order to avoid collisions with other constants.

But then, out of nowhere, a pitfall! Since your transient name is changing each time you update your plugin, WordPress is never again going to have occasion to call your transients by their old names. This means they will never be deleted! Your transients will stay in your database forever, achieving the dreaded “clutter” status that people sometimes worry about when it comes to transients. That’s one reason why it’s important to prefix all of your transients. Given that prefix, you could automatically delete all of the transients that pertain to your plugin, perhaps even providing a helpful “purge cache” button in your plugin settings page. This is a bit of a delicate matter, so I’m going to save the details for later on in the article.

Let me come clean: I have never set up a test scenario to confirm that transients might someday build up as clutter in the manner I’ve described above, but it does seem to happen in some cases. Furthermore, a reading of the core `get_transient()` function would seem to support this hypothesis. WP Engine seems to agree as well.

Also worth noting: You could grab your plugin version dynamically, from the docblock at the top of your plugin, via get_plugin_data(). However, that script only loads in wp-admin. I would imagine that you could include it on the front end as well, although I haven’t got around to trying that. I can’t vouch for it.

Using magic constants for naming your transients

Php ships with some helpful variables called magic constants, the most useful of which are __CLASS__ and __FUNCTION__. These constants return a string for the name of the current php class, and the name of the current function, respectively. This can streamline your code when it comes to naming lots of things, including transients:

<?php

class CSS_T {

  function subscribers() {

    $transient_key = __CLASS__ .'_' . __FUNCTION__;

  }

}

?>

You could easily combine this technique with the version number technique noted above.

Including your remote API key in your transient name

Most API’s require you to create a unique API key, or some other way to associate your remote calls with your account. If you find that you need to change that API key, it stands to reason that your transients would want to point to remote calls using only the new key. For this reason, you might append your API key to your transient name:

<?php

function css_t_subscribers( $limit = 50 ) {

  $api_key = 'W$3Th&j8Ias76gF%^Fukg3%$Dy3ghd!@';

  $transient_name = __FUNCTION__ . '_' . $api_key';

}

?>

You might be concerned about having your API key flying around cyberspace, as this could present a security concern. You could mitigate that by encrypting the API key, an approach that happens to have other benefits which I’ll discuss shortly.

Including the remote url and request parameters in your transient name

A remote API is going to serve a different response based on the exact url you are querying. Some examples might be:

<?php
// Getting all subscribers VS getting just 50 of them.
$subscribers       = 'https://api.example.com/subscribers';
$fifty_subscribers = 'https://api.example.com/subscribers?limit=50';

// Getting all campaigns VS getting just the ones that have already sent.
$campaigns      = 'https://api.example.com/campaigns';
$sent_campaigns = 'https://api.example.com/campaigns?status=sent';
?>

It’s very likely that your plugin will want to send many combinations of these parameters, so you’d expose them as function arguments. Given that, you can use those values to dynamically build unique transient keys for each query:

<?php

function css_t_subscribers( $limit = 50 ) {

  // The base url for getting subscribers.
  $url = 'https://api.example.com/subscribers';
  
  // Sanitize the limit variable.
  $limit = absint( $limit );
  
  // Add the limit variable to the url.
  $url = add_query_arg( array( 'limit', $limit ), $url );
  
  // Use the url in the transient name.
  $transient_name = __FUNCTION__ . '_' . $url';

}

?>

CAUTION! There is a problem!

Man, we are like drunk with appending stuff to our transient keys here! It is absolutely reasonable to have all of these elements in your transient name:

  • Plugin namespace.
  • PHP class name.
  • PHP function name.
  • Plugin version number.
  • Remote API url.
  • Remote API request parameters.
  • Remote API key.

You could end up with a transient name that is well over 100 characters long, and that won’t work. Why not? Because if you make your transient key longer than 40 characters, WordPress might not store the transient. This is because of a character limit in the options table in the WordPress database. It can be really, really easy to exceed this limit once you start prefixing, adding a version number, and adding some args. WordPress might increase this limit to 255 chars soon, but until then, the way to sidestep this issue is to compress your transient name via PHP’s md5() function.

md5() can take virtually any string and compress it down to 32 characters — a new string that is guaranteed to be unique to the string you fed it. The result is basically unreadable (it’s a hash) but there’s no reason you would need to read the transient key names, other than the prefix portion.

Given that we have as little as 40 characters to work with, and md5() uses up 32 of them, that means we only have 8 left for our prefix. For the sake of code readability, I take a bow toward the third hard problem in computer science, off by one errors (see above), and give myself only 7 characters, just to be safe:

<?php

function css_t_subscribers( $limit = '50' ) {
  
  // The namespace for our plugin.  
  $namespace = css_t_namespace(); // Let's say this gives us the slug name, 'css_tricks';
  
  // Cut it down to a max of 7 chars.
  $namespace = substr($namespace, 0, 7 );

  // The base url for getting subscribers.
  $url = 'https://api.example.com/subscribers';
  
  // Sanitize the limit variable.
  $limit = absint( $limit );
  
  // Add the limit variable to the url.
  $url = add_query_arg( array( 'limit', $limit ), $url );

  // Build a transient name that is guarenteed to carry all the uniqueness we might want, and also be less than 40 chars.
  $transient_name = $namespace . md5( $url );

}

Who knew we could go on so long on the niche topic of naming transients. It’s amazing how deep you can go with this, and it’s all because the name can be changed in interesting ways so as to break the cache. But enough about names.

Tricks for storing data in a transient

Earlier in this article, I stated that transients have three components: A name, content, and a lifespan. It’s time to look at the second portion, which is the content that you’re caching in the transient.

It doesn’t have to be a string

WordPress core tells us that we don’t need to serialize our transient content before we store it. In other words, we aren’t limited to storing simple values like strings or numbers. Rather, we can store entire arrays or objects, such as an HTTP response that comes as a result of wp_remote_request().

That said, just because you can store the entire response, that doesn’t necessarily mean you should. It might help streamline your plugin if you parse the response a bit and only store the body, or even some subset of the body. Alternatively, maybe you have a good reason for storing the entire response, maybe because you want to react to the HTTP status code elsewhere in your plugin. It’s up to you.

Not all data is worth storing

Speaking of HTTP status codes, one of the first things I’ll do when making an API integration is read the documentation and curate a list of HTTP status codes. In many API’s, a status code in the 40x or 50x range means that I made a mistake in my plugin code, making a request that the API could not fulfill. There’s probably no reason to store that in a transient, so I’ll compare the response code to my list before saving:

<?php

// Get a list of subscribers from a remote API.
function css_t_subscribers() {
  
  // Transient stuff...

  // Call the remote service.
  $response = wp_remote_get( $url );
  
  // Check our response to see if it's worth storing.
  if ( ! css_t_check_response( $response ) ) {
    return FALSE;
  }
  
}

// Given an HTTP response, check it to see if it is worth storing.
function css_t_check_response( $response ) {

  // Is the response an array?
  if( ! is_array( $response ) ) { return FALSE; }
    
  // Is the response a wp error?
  if( is_wp_error( $response ) ) { return FALSE; }

  // Is the response weird?
  if( ! isset( $response['response'] ) ) { return FALSE; }
    
  // Is there a status code?
  if( ! isset( $response['response']['code'] ) ) { return FALSE; }
    
  // Is the status code bad?
  if( in_array( $response['response']['code'], css_t_bad_status_codes() ) ) { return FALSE; }

  // We made it!  Return the status code, just for posterity's sake.
  return $response['response']['code'];

}

// A list of HTTP statuses that suggest that we have data that is not worth storing.
function css_t_bad_status_codes() {
  return array( 404, 500 );
}

?>

Only storing the result of GET requests

I’m talking about RESTful API’s here. In a restful API, you can make a request using different request types. Here are some of the most common:

  • GET – Used for getting data.
  • POST – Used for adding a row of data.
  • PUT – Used for editing an entire row of data.
  • PATCH – Used for editing part of a row of data.
  • DELETE – Used for deleting an entire row of data.

I keep talking about the wp_remote_request() family of functions, and guess what? They allow you to specify which type of request you’re making. There is only one type of request whose response belongs in a transient, and that’s a GET request. In fact, if you are making any other type of request, then you are likely trying to change data on the remote server, and that means that some of your transients might now be obsolete. This would be an occasion to dump all of the transients related to your plugin. I’ll dig into how we might do that shortly.

In the example of our email API integration, every time someone signs up for my email list, that’s my plugin sending a POST request to the remote API, to add them to my mailing list. I probably have a function in my plugin dedicated to calling that API. That function is going to detect what type of request I’m making and, if it’s not a GET request, it’s going to dump all my plugin transients.

This attitude assumes that data accuracy is more important than performance, and frankly that’s not always going to be the case. Maybe you have a view that offers many hundreds of rows of data, and that data changes very frequently. In such a case, it would not be performant to be dumping your transients on every POST request made by your plugin.

Tricks when designating a lifespan for your transient

We’re on to the third and final part of a transient: The lifespan. This can be expressed in a few different ways:

  • set_transient( $name, $content, 3600 ) – store the data for 3600 seconds, which is an hour.
  • set_transient( $name, $content, 60 * 60 ) – store the data for 60 minutes, which is an hour, only more readable.
  • set_transient( $name, $content, HOUR_IN_SECONDS ) – store the data for an hour, eminently readable. These ship with WordPress.

The “Mayfly” transient for debugging

A Mayfly is an insect that has an incredibly short lifespan. Consider the following transient:

set_transient( $name, $content, 1 )

That’s a transient that will only last for one second! This transient is almost guaranteed to never be called from the database. It would have to be generated and then re-requested in less than a second. However, this introduces a helpful way to provide a sort of debug mode in your plugin. If you are trying to debug your code, one of the most common steps is to echo your variables to see if they reflect what you’re expecting. This can be extremely frustrating with transients. You’d have to go into your API calls and comment out the transient logic in order to make sure you get fresh results for debugging, and then remember to un-comment them before deploying. Instead, I do this:

<?php

// If the user is a super admin and debug mode is on, only store transients for a second.
function css_t_transient_lifespan() {
  if( is_super_admin() && WP_DEBUG ) {
    return 1;
  } else {
    return DAY_IN_SECONDS;
  }
}

// Get subscribers, using a dynamic value for the transient time.
function css_t_subscribers() {

  // ...

  $lifespan = css_t_transient_lifespan();
  set_transient( $name, $content, $lifespan );

  // ...

}

?>

That said, if you have transients with a relatively long lifespan, such as DAY_IN_SECONDS, you’re still going to get those old values until tomorrow. Not cool. That’s what you need a way to easily purge all your plugin transients.

The purge

We need to select all of the transients that relate to our plugin, and then use the delete_transient() function to delete each one. In theory, we could delete them via SQL, but it’s usually best to do things closer to the application level, and that rule definitely applies here. I’ll explain why in a bit.

<?php

// Purge all the transients associated with our plugin.
function purge() {

  global $wpdb;

  $prefix = esc_sql( $this -> get_transient_prefix() );

  $options = $wpdb -> options;

  $t  = esc_sql( "_transient_timeout_$prefix%" );

  $sql = $wpdb -> prepare (
    "
      SELECT option_name
      FROM $options
      WHERE option_name LIKE '%s'
    ",
    $t
  );

  $transients = $wpdb -> get_col( $sql );

  // For each transient...
  foreach( $transients as $transient ) {

    // Strip away the WordPress prefix in order to arrive at the transient key.
    $key = str_replace( '_transient_timeout_', '', $transient );

    // Now that we have the key, use WordPress core to the delete the transient.
    delete_transient( $key );

  }
  
  // But guess what?  Sometimes transients are not in the DB, so we have to do this too:
  wp_cache_flush();
  
}

?>

You could call that function when a user clicks a button on your plugin settings page, when new posts are published, or perhaps whenever a widget is saved. It’s up to you!

Notice the last line in that snippet, where I’m calling wp_cache_flush. That’s because our transients might not be in the DB after all. They might actually be in the object cache!

We need to talk about object caching

Have you picked up on my cautious tone at different points in this article, eluding to the fact that transients are not always in the database? It’s because of object caching.

Recently I was trying to debug an API integration for a client. I tried to use phpMyAdmin to inspect transient values in the database, only I couldn’t find any. This is because the client was using object caching: That means their transients did not live in the database!

In order to avoid problems with object caching, all you have to do is CRUD your transients as normal, using set_transient(), get_transient(), and delete_transient(). If object caching is available, it will CRUD them in its own way.

When I say “as normal”, I mean that as opposed to doing an SQL query to handle transients. In my snippet above, I am selecting my transient via an SQL query, which is against the rules, so I have to pay a penalty. I’m opting to pay a penalty in performance and one extra line of code by calling wp_cache_flush(), which dumps the entire object cache. Comprehensive, simple, but heavy-handed. There are a couple of other ways I might choose to pay that penalty instead.

For one, it would probably be smarter to only dump the part of the cache associated with my plugin. The object cache class has methods for doing that. However, this is an article on transients, so I’m not going to deep-dive into object caching.

A different approach would be to register each of my transient keys in an array, and store that array in the database. That way, I could loop through that array and call delete_transient() on each value.

<?php

// Pass the transient key to this function whenever we save a transient.
function css_t_update_transient_keys( $new_transient_key ) {
  
  // Get the current list of transients.
  $transient_keys = get_option( 'css_t_transient_keys' );

  // Append our new one.
  $transient_keys[]= $new_transient_key;
  
  // Save it to the DB.
  update_option( 'css_t_transient_keys', $transient_keys );
  
}

// Call this function to dump our plugin transients.
function css_t_purge() {

  // Get our list of transient keys from the DB.
  $transient_keys = get_option( 'css_t_transient_keys' );
  
  // For each key, delete that transient.
  foreach( $transient_keys as $t ) {
    delete_transient( $t );
  }

  // Reset our DB value.
  update_option( 'css_t_transient_keys', array() );

} 
  
?>

It feels a little goofy to me to be making an extra database call in order to update the option, whenever we save a transient — it’s like two stones for one bird. But it’s not much code, it does not require SQL, and it plays nice with object caching.

If you want to know more about object caching, I’d suggest digging into WordPress core. For example, check out the source code for delete_transient(). You can see it checking for object caching before falling back to the normal WP options API.

Next steps

I wanted to keep this discussion focused on the Transients API, but the reality is that it is best used in conjunction with WordPress’s HTTP API, with a hint of object caching awareness as well. If you are making a plugin that makes remote calls, you should consider using the WordPress HTTP API. Abstract all those remote calls into one PHP class, and that class can easily use the WordPress Transients API before and after calling the remote service. By mastering the use of transients for your remote calls, you bring the entire web of API’s within your grasp, with minimal performance concerns.


The Deal with WordPress Transients is a post from CSS-Tricks

Go to Source

“It’s Alive!”: Apps That Feed Back Accessibly

Go to Source

It’s one thing to create a web application and quite another to create an accessible web application. That’s why Heydon Pickering1, both author and editor at Smashing Magazine, wrote an eBook Apps For All: Coding Accessible Web Applications2, outlining the roadmap for the accessible applications we should all be making.

The following is an extract from the chapter “It’s Alive” from Heydon’s book, which explores how to use ARIA live regions. Javascript applications are driven by events and the user should be informed of what important events are happening in the interface. Live regions help us provide accessible messaging systems, keeping users informed of events in a way that is compatible with assistive technologies.

Getting The Message

Picture the scene: it’s a day like any other and you’re at your desk, enclosed in a semicircular bank of monitors that make up your extended desktop, intently cranking out enterprise-level CSS for MegaDigiSpaceHub Ltd. You are one of many talented front-end developers who share this floor in your plush London office.

You don’t know it, but a fire has broken out on the floor below you due to a “mobile strategist” spontaneously combusting. Since no expense was spared on furnishing the office with adorable postmodern ornaments, no budget remained for installing a fire alarm system. It is up to the floor manager in question to travel throughout the office, warning individual departments in person.

He does this by walking silently into each room, holding a business card aloft with the word “fire” written on it in 12pt Arial for a total of three seconds, then leaving. You and the other developers — ensconced behind your monitors — have no idea he even visited the room.

Three monitors for coding
Three monitors for coding

What I cover in my eBook is, for the most part, about making using your websites and applications accessible. That is, we’re concerned with everyone being able to do things with them easily. However, it is important to acknowledge that when something is done (or simply happens), something else will probably happen as a result: there are actions and reactions.

“When one body exerts a force on a second body, the second body simultaneously exerts a force equal in magnitude and opposite in direction to that of the first body.”

– Newton’s third law of motion (Newton’s laws of motion, Wikipedia3)

Providing feedback to users, to confirm the course they’ve taken, address the result of a calculation they’ve made or to insert helpful commentary of all sorts, is an important part of application design. The problem which needs to be addressed is that interrupting a user visually, by making a message appear on screen, is a silent occurrence. It is also one which — in the case of dialogs — often involves the activation of an element that originates from a completely remote part of the document, many DOM nodes away from the user’s location of focus.

To address these issues and to ensure users (unlike the poor developers in the introductory story) get the message, ARIA provides live regions4. As their name suggests, live regions are elements whose contents may change in the course of the application’s use. They are living things, so don’t always stand still. By adorning them with the appropriate ARIA attributes, these regions will interrupt the user to announce their changes as they happen.

In the following example, we will look at how to alert users to changes which they didn’t ask for, but — like the building being on fire — really ought to know about anyway.

Alert!

Perhaps the only thing worse than a fire that could happen to the office of a web development company would be losing connectivity to the web. Certainly, if I was working using an online application, I’d like to know the application will no longer behave in the way I expect and perhaps store my data properly. This is why Google Mail inserts a warning whenever you go offline. As noted in Marco Zehe’s 2008 blog post5, Google was an early adopter of ARIA live regions.

Yellow box reads unable to reach G mail please check your internet connection
Yellow box reads unable to reach G mail please check your internet connection.

We are going to create a script which tests whether the user is online or off and uses ARIA to warn screen reader users of the change in this status so they know whether it’s worth staying at their desk or giving up and going for a beer.

The Setup

For live regions, ARIA provides a number of values for both the role and aria-live attributes. This can be confusing because there is some crossover between the two and some screen readers only support either the role or aria-live alternatives. It’s OK, there are ways around this.

At the most basic level, there are two common types of message:

  1. “This is pretty important but I’m going to wait and tell you when you’re done doing whatever it is you’re doing.”
  2. “Drop everything! You need to know this now or we’re all in big trouble. AAAAAAAAAAGHH!”

Mapped to the respective role and aria-live attributes, these common types are written as follows:

  1. “This is pretty important but I’m going to wait and tell you when you’re done doing whatever it is you’re doing.” (aria-live="polite" or role="status")
  2. “Drop everything! You need to know this now or we’re all in big trouble. AAAAAAAAAAGHH.” (aria-live="assertive" or role="alert")

When marking up our own live region, we’re going to maximize compatibility by putting both of the equivalent attributes and values in place. This is because, unfortunately, some user agents do not support one or other of the equivalent attributes. More detailed information on maximizing compatibility6 of live regions is available from Mozilla.

Since losing internet connectivity is a major disaster, we’re going to use the more aggressive form.

<div id="message" role="alert" aria-live="assertive" class="online">
    <p>You are online.</p>
</div>

The code above doesn’t alert in any way by itself — the contents of the live region would have to dynamically change for that to take place. The script below will run a check to see if it can load test_resource.html every three seconds. If it fails to load it, or it has failed to load it but has subsequently succeeded, it will update the live region’s class value and change the wording of the paragraph. If you go offline unexpectedly, it will display <p>There’s no internets. Time to go to the pub!</p>.

The change will cause the contents of that #message live region to be announced, abruptly interrupting whatever else is currently being read on the page.

// Function to run when going offline

var offline = function() {
  if (!$('#message').hasClass('offline')) {
    $('#message') // the element with [role="alert"] and
[aria-live="assertive"]
.attr('class', 'offline') .text('There\'s no internets. Go to the pub!'); } } // Function to run when back online var online = function() { if (!$('#message').hasClass('online')) { $('#message') // the element with [role="alert"] and
[aria-live="assertive"]
.attr('class', 'online') .text('You are online.'); } } // Test by trying to poll a file function testConnection(url) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onload = function() { online(); } xmlhttp.onerror = function() { offline(); } xmlhttp.open("GET",url,true); xmlhttp.send(); } // Loop the test every three seconds for "test_resource.html" function start() { rand = Math.floor(Math.random()*90000) + 10000; testConnection('test_resource.html?fresh=' + rand); setTimeout(start, 3000); } // Start the first test start();
Alert reads alert there’s no internets. Go to the pub.
Alert reads “Alert: there’s no internets. Go to the pub!”

There are more comprehensive ways to test to see if your application is online or not, including a dedicated script called offline.js7, but this little one is included for context. Note that some screen readers will prefix the announcement with “Alert!”, so you probably don’t want to include “Alert!” in the actual text as well, unless it’s really, really important information.

There is a demo of this example8 available.

test.css

We would like to maximize compatibility of live regions across browsers and assistive technologies. We can add a rule in our test.css to make sure equivalent attributes are all present like so:

[role="status"]:not([aria-live="polite"]), 
[role="alert"]:not([aria-live="assertive"]) {
	content: 'Warning: For better support, you should include
a politeness setting for your live region role using the
aria-live attribute'; } [aria-live="polite"]:not([role="status"]), [aria-live="assertive"]:not([role="alert"]) { content: 'Warning: For better support, you should
include a corresponding role for your aria-live
politeness setting'; }

I Want The Whole Story

“Taken out of context, I must seem so strange.”

– Fire Door by Ani DiFranco

By default, when the contents of a live region alter, only the nodes (HTML elements, to you and me) which have actually changed are announced. This is helpful behavior in most situations because you don’t want a huge amount of content reread to you just because a tiny part of it is different. In fact, if it’s all read out at once, how would you tell which part had changed? It would be like the memory tray game where you have to memorize the contents of a tray to recall which things were removed.

Tray full of bits of HTML
Tray full of bits of HTML

In some cases, however, a bit of context is desirable for clarification. This is where the aria-atomic attribute comes in. With no
aria-atomic set, or with an aria-atomic value of false, only the elements which have actually changed will be notified to the user. When aria-atomic is set to true, all of the contents of the element with aria-atomic set on it will be read.

The term atomic is a little confusing. To be true means to treat the contents of this element as one, indivisible thing (an atom), not to smash the element into little pieces (atoms). Whether or not you think atomic is a good piece of terminology, the expected behavior is what counts and it is the first of the two behaviors which is defined.

One atom compared to lots of atoms
One atom compared to lots of atoms

Gez Lemon offers a great example of aria-atomic9. In his example, we imagine an embedded music player which tells users what the currently playing track is, whenever it changes.

<div aria-live="polite" role="status" aria-atomic="true">
  <h3>Currently playing:</h3>
  <p>Jake Bugg — Lightning Bolt</p>
</div>

Even though only the name of the artist and song within the paragraph will change, because aria-atomic is set to true the whole region will be read out each time: “Currently playing: Jake Bugg — Lightning Bolt”. The “Currently playing” prefix is important for context.

Note that the politeness setting of the live region is polite not
assertive as in the previous example. If the user is busy reading something else or typing, the notification will wait until they have stopped. It isn’t important enough to interrupt the user, not least because it’s their playlist: they might recognize all the songs anyway.

Box showing a graphic equalizer which reads currently playing, Jake bug lightning bolt
Box showing a graphic equalizer which reads currently playing, Jake bug lightning bolt

The aria-atomic attribute doesn’t have to be used on the same element that defines the live region, as in Lemon’s example. In fact, you could use aria-atomic on separate child elements within the same region. According to the specification:

“When the content of a live region changes, user agents SHOULD examine the changed element and traverse the ancestors to find the first element with aria-atomic set, and apply the appropriate behavior.”

Supported States and Properties10

This means we could also include another block within our live region to tell users which track is coming up next.

<div aria-live="polite" role="status">

   <div aria-atomic="true">
     <h3>Currently playing:</h3>
     <p>Jake Bugg — Lightning Bolt</p>
   </div>

   <div aria-atomic="true">
     <h3>Next in queue:</h3>
     <p>Napalm Death — You Suffer</p>
   </div>

</div>

Now, when Jake Bugg’s Lightning Bolt is nearing an end, we update the <p> within the next in queue block to warn users that Napalm Death are ready to take the mic: “Next in queue: Napalm Death — You Suffer”. As Napalm Death begin to play, the currently playing block also updates with their credentials and at the next available juncture the user is reminded that the noise they are being subjected to is indeed Napalm Death.

aria-busy

I was a bit mischievous using Napalm Death’s You Suffer as an example track because, at 1.316 seconds long, the world’s shortest recorded song would have ended before the live region could finish telling you it had started! If every track was that short, the application would go haywire.

In cases where lots of complex changes to a live region must take place before the result would be understandable to the user, you can include the aria-busy attribute11. You simply set this to true while the region is busy updating and back to false when it’s done. It’s effectively the equivalent of a loading spinner used when loading assets in JavaScript applications.

Typical loading spinner labelled ARIA atomic true
Typical loading spinner labelled ARIA atomic true

Usually you set aria-busy="true" before the first element (or addition) in the live region is loaded or altered, and false when the last expected element has been dealt with. In the case of our music player example, we’d probably want to set a timeout of ten seconds or so, making sure only music tracks longer than the announcement of those tracks get announced.

$('#music-info').attr('aria-busy', 'true');

// Update the song artist & title here, then...

setTimeout(function() {
   $('#music-info').attr('aria-busy', 'false');
}, 10000);

Buy The eBook

That concludes your extract from “It’s Alive!”, a chapter which goes on to explore the intricacies of designing accessible web-based dialogs. But that’s not all. There’s plenty more about creating accessible experiences in the book, from basic button control design to ARIA tab interfaces and beyond. Reviews for the eBook and purchasing options are available here12. The inimitable Bruce Lawson has written a lovely post13 about it, too.

Footnotes

  1. 1 https://twitter.com/heydonworks
  2. 2 https://shop.smashingmagazine.com/apps-for-all-coding-accessible-web-applications.html
  3. 3 http://en.wikipedia.org/wiki/Newton%27s_laws_of_motion
  4. 4 https://developer.mozilla.org/en-US/docs/Accessibility/ARIA/ARIA_Live_Regions
  5. 5 http://www.marcozehe.de/2008/08/04/aria-in-gmail-1-alerts/
  6. 6 https://developer.mozilla.org/en-US/docs/Accessibility/ARIA/ARIA_Live_Regions
  7. 7 http://github.hubspot.com/offline/docs/welcome/
  8. 8 http://heydonworks.com/practical_aria_examples/#offline-alert
  9. 9 http://juicystudio.com/article/wai-aria_live-regions_updated.php
  10. 10 http://www.w3.org/TR/wai-aria/states_and_properties#aria-atomic
  11. 11 http://www.w3.org/TR/wai-aria/states_and_properties#aria-busy
  12. 12 https://shop.smashingmagazine.com/apps-for-all-coding-accessible-web-applications.html
  13. 13 http://www.brucelawson.co.uk/2014/apps-for-all-coding-accessible-web-applications-book-review/

The post “It’s Alive!”: Apps That Feed Back Accessibly appeared first on Smashing Magazine.

Go to Source

50+ incredible freebies for web designers, April 2015

Go to Source

Amazing designers and developers release new projects every day, that make us excited, inspired, and often more than a little impressed.

Today we’re continuing our monthly roundup of the best free resources for web designers, and there’s something for everybody, whether you’re a designer, a developer, or  a bit of both. We’ve got UI kits, icon packs, mockups, themes, templates, and more tools than you can use in a month. So free up some hard drive space, then browse through these downloads, enjoy!

1450 Free Vector Icons

SmartIcons is a project that’s putting together thousands of useful icons into a smart icon system and giving them away for free.

1450 Free Vector Icons

 

Flatflow Icons for Sketch

A pretty cool set of icons in a flat style, editable with Sketch. Free for personal and commercial use.

Flatflow Icons for Sketch

 

Flat Web Design Icons

An awesome package of icons with a fresh flat design style, containing elements related to web and graphic design.

Flat Web Design Icons

 

A3 Poster Frame Mockups

A clean set of mockups for you to test-drive your latest poster design. Make use of cool lighting effects and multiple perspectives.

A3 Poster Frame Mockups

 

Creative Poster Template

A good-looking poster design for creative people wanting to promote themselves or their events. It comes with a lot of icons and can be edited in Illustrator, Photoshop and InDesign.

Creative Poster Template

 

 

A4 Landscape Brochure Mockup

A neat brochure mockup with multiple lighting effects, smart objects and transparent backgrounds.

A4 Landscape Brochure Mockup

 

Pebble Time Design Kit

The new Pebble Time has created quite a stir, and the design community is no different. Here’s a set of mockups for the upcoming gadget.

Pebble Time Design Kit

 

Adorable Flat Workspaces

Make cool desks by interchanging the elements on the table, using one of the three different color combinations available.

Adorable Flat Workspaces

 

Pretty Vintage Text Effect

This Photoshop effect will bring up your texts by giving them an impressive 3D appearance, managing to truly highlight their importance.

Pretty Vintage Text Effect

 

500 Hipster Vector Designs

A rather hefty package of fully vector designs, all editable in Adobe Illustrator. They will allow you to create posters, badges and many other elements.

100 Free Hipster Vector Designs

 

Apple Watch UI Kit for Sketch

An awesome set of carefully crafted design elements for the Apple Watch, editable only through Sketch 3.

Apple Watch UI Kit for Sketch

 

iCollection UI Kit

Three app designs put together in one so you can take them apart and make your own creations based on them.

ICollection UI Kit

 

Smart UI Kit Lite

A complete set of clean interface elements for Sketch that you can use to set upyour own websites and applications.

Smart UI Kit Lite

 

Vector UI Components

A set of vector components composed of mostly graphs and charts, but also including other elements for media playback, weather and general use.

Vector UI Components

 

iOS 8 GUI Kit

A complete set of design elements for Apple’s latest iOS version. It’s all made up of vector shapes, editable with Illustrator.

iOS 8 GUI Kit

 

Canaro Font

A modern-looking font that resulted from the exploration of geometrical type designs of the early 20th century.

Canaro Font

 

Bough: Hand-Drawn Typeface

A cool hand-made font with an old school feel to it. It comes with alternate glyphs to achieve a different look each time you use it.

Bough: Hand-Drawn Typeface

 

Streetwear Free Font

A fancy font with a hand-written and vintage feel that you can use for big designs such as posters, t-shirts or branding.

Streetwear Free Font

 

Moscú Free Font

An impressive typeface inspired by Russian constructivism featuring striking shapes and unexpected glyphs.

Moscú Free Font

 

Muller Font

Meant to be the ultimate universal font, Muller works perfectly across all sizes and purposes.

Muller Font

 

Trekking Store PSD Template

A fantastic website template, mostly fit for e-commerce websites that want to feature a familiar, modern look. Editable with Adobe Photoshop.

Trekking Store PSD Template

 

Profile: Website PSD File

Profile started with a fantastic mountain image and developed into a top-class theme choice for any business website.

Profile: Website PSD File

 

The Singhs: E-commerce PSD Template

A very elegant and complete template for your next online store, containing more than 20 PSD files for all the different pages you could need.

The Singhs: E-commerce PSD Template

 

Chromatic WordPress Theme

A neat WordPress theme, best suited for business or personal websites. Works great on any device thanks to its responsive design.

Chromatic WordPress Theme

 

Express: Responsive Magazine WordPress Theme

A magazine WordPress theme with a strong focus on performance, boasting the popular flat design style.

Express: Responsive Magazine WordPress Theme

 

 

Web Design WordPress Theme

A theme with a rather universal design and easy customization options, making it fit for a great number of websites, no matter the topic they talk about.

Free Multi Web Design WordPress Theme

 

Spectral

This modern HTML template comes with fancy animations and fully responsive design. Simple and effective, Spectral seems like a great match for the modern web.

Spectral

 

Barrier: Business Template

Barrier is a superb template featuring a simple look with Font Awesome icons, portfolio carousel, contact form and many other features.

Barrier: Business Template

 

Motion Blur Experiment

This piece animates a modal window once you click on a button, featuring a fancy motion blur effect as the dialog moves.

Motion Blur Experiment

 

Motion Blur Effect

A motion blur effect created with CSS and JavaScript. You can choose to check it in text or image version.

Motion Blur Effect

 

Dropdown Menus Example

Simple but good looking multi-level navigation exercise, great for your next website development.

Dropdown Menus Example

 

Animated Twitter Button

An awesome animated effect that turns the black screen blue once you hover over the logo button. 

Animated Twitter Button

 

React Sign Up Form Example

A beautiful sign up form with a flat style, info validation, animations and hover effects.

React Signup Form Example

 

Segment

Segment is a tool that helps you gather customer data and manage it in many useful ways to improve your apps and user experience.

Segment

 

RAD.js

A mobile app framework for all major mobile systems and even Web browsers. It focuses on ease of use and speed.

RAD.js

 

APIembed

Simplify the coding process for various languages by letting APIembed generate snippets automatically for you.

APIembed

 

ApplePie: A Better Way to Build Web Interfaces

A bold initiative that intends to bring standards to front-end development, providing a set of conventions. ApplePie even has its own toolkit to get you started.

ApplePie: A Better Way to Build Web Interfaces

 

Cachet HQ

Thanks to this open source project, you can keep your users in the loop about the recent status of your service through a simple, comprehensive page.

Cachet HQ

 

Dropplets

A new blogging platform with no database that intends to make the publishing process as easy as can be.

Dropplets

 

Material UI

An HTML5 interface that thoroughly follows Google’s Material Design guidelines. It serves as a great test to gauge Material’s potential in the future Web.

Material UI

 

Layers

This interesting WordPress site builder is installed just like a regular theme, but then offers a staggering amount of choices to put together the blog you have in your mind. Best of all, it’s totally free!

Layers

 

UIkit: Modular Front-end Framework

A lightweight front-end framework featuring a modular approach and lots of customization options. As you’d expect these days, it’s more than ready to take on mobile-first projects.

UIkit: Modular Front-end Framework

 

OpenUI5

This tool aims to help you create fantastic web applications that will run on any device, letting you focus on what’s really important.

OpenUI5

 

Salvattore

Use this jQuery tool to create amazing grids, customizable through CSS.

Salvattore

 

Dug.js

With Dug.js, you can gather feeds in JSONP (Dribbble, Instagram, Pinterest and many more) and easily display them in your website as HTML script.

Dug.js

 

Sift.js

This useful library uses the power of the MongoDB query language to filter information according to your preset parameters.

Sift.js

 

Space.js

Turn your website into a nice presentation handled with the mouse wheel, using multiple customization settings.

Space.js

 

SedotPress

A lightweight blogging platform created in PHP. No database is required, as all data is saved in JSON format.

SedotPress

 

Responsible.js

Use Responsible.js to give your users the power to choose between mobile and desktop versions of your site in order to achieve the best viewing experience.

Responsible.js

 

FullPage.js

A simple resource to create good looking full-screen scrolling websites in both vertical and horizontal directions.

FullPage.js

 

Cayley

Cayley is a Google-run open source graph that aims to be included in the developer’s toolbox when linked and graph-shaped data are involved.

Cayley

200 Premium Stock Images with Room for Text – only $18!
50+ incredible freebies for web designers, April 2015

Source
Go to Source

Collective #165

Go to Source

Collective165_kubist

Kubist

A fantastic app that transforms an ordinary image into a cubism-like composition. Made by William Ngan. Read about how it works in this article.

Check it out

Advertisement

Collective165_fi

Project Fi

Project Fi by Google is a program to deliver a fast, easy wireless experience in close partnership with leading carriers, hardware makers, and our users.

Check it out

Collective165_eggjs

egg.js

A JavaScript library for easily adding easter eggs to web pages by watching the user’s key strokes. Made by Mike Flynn.

Check it out

Collective165_peekspace

Peekspace

A curated collection of free to use space related photography by Patrick Goethe.

Check it out

Collective #165 was written by Pedro Botelho and published on Codrops.


Go to Source

How to Customize the WordPress Text Editor to Look and Function Like Your Front-End

Go to source

Though WordPress is increasingly on the verge of becoming a fully-fledged application framework, the humble post editor remains the area of the interface users spend most of their time in.

It’s a part of the backend that’s seen significant improvements over the last number of years – the recent move to version 4.0 of TinyMCE  in WordPress 3.9 being a highlight – but there’s still plenty of room for improvement.

One of the most common problems users have with the editor is the need to constantly switch between editing and preview modes to see how content will actually look live.

In this article we’ll tackle that exact issue and break down how to customize the WordPress text editor to look and function like your front-end design.

Why Would I Want to Customize the Editor?

When you’re busy bashing out an initial draft of a post or page, the final look and feel of the text is the last thing on your mind. What matters is getting your thoughts down and – as Steven Pressfield so elegantly put it – covering the canvas.

As you move on to the serious business of editing and revising however, the fact that your content exists in a context becomes ever more important. Typically, this manifests itself as heavy reliance on the built-in Preview button.

Let’s be clear – there’s nothing intrinsically wrong with the Preview button. It’s a fantastic piece of functionality to have at your fingertips.

If you’re simply popping in to update a line or two in an article, it’s a great way to check your changes before hitting Publish. If you need to give an article a thorough proofreading before submitting for review, it’s similarly useful.

Where it’s very far from ideal is in the daily cut and thrust of putting together a main draft. In fact, when you’re working on a longform piece over a potentially slow remote connection it can quickly become a major problem for two significant reasons:

  1. Context switching: Writing is about getting into a groove. Once you’re in it, you want to stay there. Having to constantly switch between browser windows and different visual contexts is a killer for focus and flow.
  2. Time: All those roundtrips between the editor and the preview window add up over the course of a working week. Test it yourself. The next time you’re working on a piece, make a note of how often you switch tabs. That’s time that could have been spent polishing the actual content.

By customizing the editing screen to match your front-end display, you remove the need to constantly preview your work. It makes the editor far more of a genuine WYSIWYG tool.

For example, maybe you’re worried a particular paragraph is slightly too long given the generous line-height and font-size your theme employs (as seen here on WPMU DEV). Customize your post editor and the end results are right there on the screen in front of you as you type.

Taking the extra time to customize the backend has a couple of further major advantages also worth pointing out:

  1. It makes it far easier for non-technical team members to input content in a context that will be instantly familiar to them.
  2. It makes a great high-end finishing touch to add when you’re preparing a site for an external client who might be coming to WordPress for the first time.

What About Front-End Editors?

Some of you may well be asking at this point: what about front-end content editors? Isn’t this what they’re designed to do? And wasn’t there talk of the Front-end Editor plugin being built into the next release of WordPress as a core feature?

Good questions. Let’s take them one at a time.

Front-end editors are a fashionable feature and one that’s being increasingly strongly pushed by competitors to WordPress such as Squarespace and Weebly; not to mention our very own Upfront theme.

The great promise of these editors is that they let non-technical users interact directly with the content of a website to make changes. They can be perfect if you’re just looking to make small changes to existing sections of content and are usually a snap for less experienced admins or site owners to use, assuming they’re set up correctly.

The downside is the restricted range of functionality such solutions typically offer – both in terms of editing itself and lack of access to advanced post features such as meta boxes. They also put a barrier between you and the functionality on offer in the rest of the backend admin.

Then there’s the issue of editorial workflow and control to consider. A front-end editor is great if you want people to just be able to go in there and change things immediately, but that is very much not always the case.

The final sticking point is the issue of complexity. Putting together a solid front-end editor is no trivial undertaking. Many of the best plugins out there are commercial offerings, meaning you’re adding another level of paid dependency to your setup and having to worry about future compatibility with other parts of your theme.

In short, it’s a complex issue. For good arguments on both sides we’d recommend our own Chris Knowles’ reasoned case against and Fred Meyer’s equally impassioned case for.

WordPress Front-end Editor
The WordPress Front-end Editor plugin.

Many of us were hoping some of that complexity would be mitigated by the inclusion of the Front-End Editor plugin in WordPress core.

Sadly, after much initial excitement, those hopes were destined eventually to be dashed.

From late 2013 up until late November 2014, this plugin was under active development as a Feature Plugin meaning it was scheduled for eventual release into core.

The project has unfortunately stalled since then, and been moved on to the Inactive Feature Plugins list. Sadly, it’s safe to say we won’t be seeing its appearance in core anytime soon.

If you are interested in trying out a front-end editor then we’d recommend trialling either the Front-end Editor (free), Visual Composer (paid) or Live Composer (paid), but be aware of the potential complications we’ve mentioned above.

The approach we’re going to take in this article, on the other hand, gives you a simple way of skirting around these snags and getting down to the matter at hand: making your content sing.

Let’s start making it happen.

Setting the Stage

Every site will naturally have different content and potentially wildly different theme implementations. For the purposes of this article, we’re going to strip things down to give you a solid understanding of the basics that you’ll then be free to apply to the particular requirements of your own setup.

We’ll be using a local setup of WordPress and starting with a version of the WordPress Theme Unit Test data to illustrate our points. If you’re starting to look at customizing your own environment, taking this approach offers a couple of obvious benefits:

  1. By developing locally, you’re free to experiment without risking disruption to your users or co-workers.
  2. The WordPress Theme Unit Test data gives you a sensibly organized set of core content to test your changes against. It’s the perfect platform to start with when exploring theme changes of any kind, on both the front and back end.

In our case, after downloading and imported the starter pack from WP Test on a fresh local WordPress install, we selected Twenty Fifteen as the theme.

This combination gives us a number of well-organized pages, such Markup and Formatting and Image Alignment, to play with straight out of the box.

WP Test page markup example
WP Test’s Markup and Formatting page.

If you’re following along, you can either replicate this approach or simply activate your own theme on a local install with your current site content.

We recommend the former as an initial stage. The content provided by WP Test is an excellent way of checking how complete your current theme’s styling is before you start making major changes to it.

Understanding What’s Going On Under the Hood

Now that we have some sensible sample content to look at, let’s take some time to understand what’s actually going on under the hood in WordPress before we look at customizing the editor itself.

As we mentioned at the top, WordPress ships with the open source TinyMCE editor as standard. This is, so to speak, the bottom of the theming stack.

TinyMCE has its own stylesheet that controls how content is displayed within it. By default, this is blissfully unaware of the outside world. The developers of TinyMCE were sensible enough to make room for additional stylesheets to be loaded into it, however, via a hook called content_css.

For their part, the developers of WordPress were kind enough to wrap this in a native function called add_editor_style. This has been included in WordPress core since version 3.0.0.

If you consult the online documentation, you’ll see this function is tucked away in wp-includes/theme.php. We’ll be looking at ways of calling this function directly in just a few minutes.

By default, WordPress use this function to check for the presence of a CSS file in your theme’s root directory called editor-style.css that it can use to style the contents of the editor.

So, if you are looking to customize an existing theme, one of the first questions you have to ask yourself is does an editor-style.css file already exist in your theme?

If we take the Twenty Fifteen theme as an example, we can see that it does indeed include such a file. A quick toggle between the preview and admin views of our Markup and Formatting page shows that the core styles are being faithfully replicated between environments.

Editor and Preview window text comparison
Text in Editor window on the left and Preview on the right.

Let’s take it a step further and doublecheck that the styling we’re seeing in the editor window is definitely being controlled by editor-style.css. A quick trip to the Web Inspector is all we need to confirm that this is the case.

WordPress post editor default CSS styles
By default, the editor looks for editor-style.css

Hopefully the basic scenario is relatively clear at this stage. To recap:

  • The WordPress editor is powered by TinyMCE.
  • TinyMCE allows its default styling to be overridden.
  • WordPress uses a function called add_editor_style to specify which CSS file should be used to override default styling.
  • By default, WordPress looks for a file called editor-style.css in the root of the active theme.

The next question is how to handle making your own changes.

Making Your Own Changes

As suggested above, the first thing that needs to be cleared up is the question of whether there’s a default editor stylesheet file in place in the root of your theme’s folder.

If there is, we suggest making a copy in the same location and calling it custom-editor-style.css. This gives you a clean place to start experimenting and an easy way to revert to the original setup.

If there is no file in place, create a new file called custom-editor-style.css and place it in the root of your theme folder.

Connecting Your Custom CSS

Our next step is telling WordPress to look for our new file rather than the default. We’ll do this by adding an override in our theme’s functions.php to call add_editor_style and tell it to use our new stylesheet.

Open up your theme’s functions.php, add the following lines at the end, and save.

Now let’s check that our editor is actually using the new stylesheet. Again, a quick trip into the Inspector is all we need to be sure. As you can see below, we’ve now successfully established a connection with our new file.

Browser inspector tool showing filepath of CSS file.
The custom version of editor-style.css is being loaded.
Changed editor header styling with CSS
Headers changed to green.

Now let’s make a couple of quick changes to the CSS file to make sure they’re being picked up on the backend.

First of all I’m going to make those headers a fetching shade of green by editing custom-editor-style.css.

The headers were changed by adjusting the following CSS:

Example of changing image properties via CSS
Changing image border color to pink in the Editor.

And now let’s add a subtle border to our images.

#tinymce, in case you were wondering, is the ID automatically assigned to the <body> tag in the TinyMCE editor.

We’ll be able to see the results of this change immediately via the Image Alignment page.

We won’t be placing in any CSS showcases in the near future, but from these two simple examples it’s clear that we now have complete control over the contents of the editor window. The pink border, incidentally, was created with the following CSS:

From this point on it’s a question of going through your existing CSS and making sure it matches your editor in the ways that make the most sense for your use case.

Using Your Existing Front-End Stylesheet as a Base

If you don’t have an existing editor stylesheet to work off like we did here, you can also import your site’s existing front-end stylesheet to use as a base. Let’s have a quick look at how to do that.

To import your existing front-end style sheet, simply replace the contents of custom-editor-style.css with the following:

Things are likely to look a little broken at first when you do this, but you’ve got a nice separation of concerns in place and a solid base from which to work.

Going Further

The next steps to take will depend on exactly how far you want to go in terms of matching the front-end display to the editor. We’d suggest having a good look at the editor-style.css stylesheet that ships with Twenty Fifteen as a starting point for mapping out your CSS strategy.

Also be sure to consult the WordPress documentation for pointers on how to take this approach further with more advanced features like adding custom styles based on post type.

Before we wrap up, we should also mention a few other TinyMCE customizations you might want to explore:

Conclusion

Taking control over the display of the editor window in WordPress will save you time as a writer and add an extra layer of professional polish to your theme.

By understanding how styles are applied, you’re in a position to customize as much or as little as the situation demands.

Let’s recap the steps:

  1. Check if your theme ships with an editor-style.css stylesheet.
  2. Create your own custom stylesheet and point WordPress to it.
  3. Use either the existing editor stylesheet as a base or import your main theme style.
  4. Get styling.

We hope this article helps you along the way to taking control of your working environment.

Example of changing image properties via CSS
Changing image border color to pink in the Editor.

Enter here your text …

If you have any related tips or tricks to share, tell us about them in the comments below!

Related posts:

  1. How to Customize the WordPress Post Editor Did you know you can easily modify the style of…
  2. Display the Full TinyMCE Editor In WordPress In today’s Weekend WordPress Project, I’ll show you how to…
  3. Your Totally Complete Guide to Customizing the WordPress Post Editor The WordPress Post Editor is great, but sometimes it’s just…

Our favorite tweets of the week: April 20, 2015 – April 26, 2015

Go to Source

Every week we tweet a lot of interesting stuff highlighting great content that we find on the web that can be of interest to web designers.

The best way to keep track of our tweets is simply to follow us on Twitter, however, in case you missed some here’s a quick and useful compilation of the best tweets that we sent out this past week.

Note that this is only a very small selection of the links that we tweeted about, so don’t miss out.

To keep up to date with all the cool links, simply follow us @DesignerDepot

How to Design for Virtual Reality http://depot.ly/M3eta

 

An Interview with Rochelle King, Global VP of Design at Spotify http://depot.ly/M3efU

 

Some Common Legal Misunderstandings About Image Usage http://depot.ly/M3e8L via @speckyboy

 

Imagine Color Names Correctly With The Help of Color Thesaurus http://depot.ly/LZMmv

 

RT @speckyboy: Create an Image Preview from a Video http://depot.ly/LZMjc

 

How I manage a social media platform of over 11 million followers every day http://depot.ly/LZM1H /@buffer

 

15 inspiring entrepreneurs who built careers around their passions through social media http://depot.ly/LZLMg

 

In Pieces: A rare specimen of #CSS-based animation http://depot.ly/LZJoI

 

Learn to create forms that improve user experience http://depot.ly/LZLx3 #ux

 

6 problems with motion design education http://depot.ly/LZJpT via @motionographer

 

Apple buys a forest the size of San Francisco for conservation, will build 2 new solar farms http://depot.ly/LWyoe

 

Big Data explained in less than 2 minutes – to absolutely anyone http://depot.ly/LWykw

 

1,500 iOS apps have HTTPS-crippling bug. Is one of them on your device? http://depot.ly/LWxBV

 

Why can’t retailers prevent their sites from crashing when they unveil a big-deal designer collaboration? http://depot.ly/LWxxB

 

WordPress 4.1.2 is a Critical Security Release, Update Recommended http://depot.ly/LWxjx

 

Google says there are 4.7% more mobile friendly websites today than 2 months ago http://depot.ly/LWwEF /@sengineland

 

Reuben Wu’s photographs of uncommon places look like alien landscapes http://depot.ly/LTWeA via @designboom

 

Google Street View dives into the legend of Nessie, the Loch Ness monster http://depot.ly/LTW47

 

‘Puss Puss’ mag is deadly serious http://depot.ly/LQ2bf

 

Want more? No problem! Keep track of all our tweets by following us @DesignerDepot

200 Premium Stock Images with Room for Text – only $18!
Our favorite tweets of the week: April 20, 2015   April 26, 2015

Source
Go to Source

How to Cloak Your Links to Protect Your WordPress Site’s Revenue

Go to source

Whether you’re earning extra income as an affiliate or you’re running your own program or online store with digital products, your revenue can slip through your fingers if you don’t protect your links.

Your digital file URLs can be endlessly shared and downloaded if you don’t set limits for their use, while long affiliate links can look suspicious to visitors who are not seasoned in affiliate marketing. You can also lose credit for a sale if a user clicks multiple referring links.

These are some of the most common ways you can miss out on revenue, but in this Weekend WordPress project, we’ll cover the best plugins for easily correcting these loopholes to help you keep the cash you have rightfully earned.

  • MarketPress eCommerce

    MarketPress eCommerce plugin by WPMU DEV

    MarketPress is our complete e-commerce plugin that helps you sell your products online – even digital ones – and you can be sure your downloadable items are safe.

    Your links are protected in three ways:

    1. The download is only available to the person who has the confirmation email.
    2. You can set a limit to how many times your file is downloaded per customer, per sale.
    3. You can enable forced logins in order to complete a purchase so that links can only be accessed by the customer if they are logged in.

    There are many other features included which is why it’s a popular choice for WordPress users. It’s a premium plugin worth its weight in gold (or electromagnetic waves.)

  • Affiliates

    Affiliates plugin by WPMU DEV

    Affiliates is another one of our plugins that can help you create a fully automated affiliate program for your site. It also does a fantastic job of tracking the source of the referring traffic in two ways to ensure your affiliates are protected from losing out on potential revenue.

    Once signed up, affiliates can enter the URL of the site where the link will be placed. Once clicked, the Affiliates plugin recognizes the referring URL and pairs it with the active account to ensure revenues are counted.

    The plugin uses a browser cookie to track referral links. When an affiliate link is clicked, a cookie is created in the user’s browser. When a purchase is completed, the plugin recognizes the cookie and uses it to identify the referral URL and the corresponding affiliate account.

    The cookies also help by giving credit to the first referring link that’s clicked if many are used.

    This premium plugin fully integrates with the MarketPress eCommerce plugin and has many other useful features that help to make creating affiliate programs easy and seamless.

  • Pretty Link Lite

    Pretty Link Lite plugin

    Pretty Link Lite is a popular plugin that acts like link shrinking service such as tinyurl.com or bit.ly. The magnificent difference is that Pretty Link Lite lets you use your own domain. If you’re already an affiliate, you can clean up the links you already have with this plugin to make it more user-friendly.

    You can also track the usage of your pretty links and the plugin provides a detailed report of each hit.

    It’s no wonder why this plugin has over 100,000 active users. It’s free to use, but also has a premium version in case you would like to access more features.

  • WP Wizard Cloak

    WP Wizard Cloak plugin

    WP Wizard Cloak also lets you use your own domain to mask long affiliate links and shorten them to something more desirable. You can also generate and export detailed reports for each click of your links.

    You can also send visitors to different URLs based on their country of origin. This can be useful if you are an Amazon affiliate, for example, as you can send users to their country’s version of the Amazon website for their convenience.

    It’s a plugin worth exploring since it has other useful features and it’s free, too.

  • ThirstyAffiliates

    ThirstyAffiliates plugin

    The ThirstyAffiliates plugin not only cloaks and shortens links using your own domain name, but it also lets you further protect your links with 301 redirection to ensure your visitors are consistently guided to the page you want them to see and only that page.

    This plugin also makes it really easy to add your affiliate links into your site’s posts or pages in the editor. You can even turn your links into shortcodes for further customization with custom CSS styling.

    It’s a lightweight plugin with many more helpful features at no cost. If you find you want more features down the road, there are many available as premium add-ons.

  • Easy Affiliate Links

    Easy Affiliate Links plugin

    Easy Affiliate Links is a brand new plugin that lets you shorten your affiliate links by cloaking them, but you can also assign categories to your links to help keep you organized. You can also easily access all your links in both the visual and HTML editor to easily add them to your posts and pages.

    There are also many features that are planned for future version including analytics, A/B testing, specific links by geography and a broken link checker.

    It may be a brand new plugin, but it’s gaining steam fast with over 75 active installs in the first 24 hours since this plugin was added to the WordPress directory. It’s a solid plugin that’s worth checking out.

Conclusion

With these plugins, you’ll be a few steps closer to protecting your links and the revenue they generate for you. It’s as easy as installing a plugin (or two) and setting up a few simple options.

If you’re interested in other ways you can protect your site, check out some of our other posts including WordPress Security: The Ultimate GuideHow To Protect Email Addresses On Your WordPress Site and How to Use SSL and HTTPS with WordPress.

Do you think there is a plugin that’s missing from this list? Feel free to share it in the comments below.

Related posts:

  1. WordPress Security: The Ultimate Guide Like most website owners, security was never top of my…
  2. How To Protect Email Addresses On Your WordPress Site Your WordPress is still being scraped for email addresses. In…
  3. How to Use SSL and HTTPS with WordPress Everyday we give away our personal information on the internet….