User experience quantified: maximizing lifetime value

UX is such a fuzzy term; honestly, that’s one thing I can’t stand about it. Ask 10 different professionals what it means and you might get 10 different answers.

Most would probably agree that user experience is the perception a user has of their interaction with a system. So, good UX means creating a good perception of some system?

That’s all good, but it doesn’t get to the root of the issue. The question that really interests me is, why would I want to spend time and effort creating that positive perception?

Some of the softer UX philosophies advocate delighting the user or bringing them joy. But that begs the same question: why?

Clearly there is a benefit to making sure the user experience is incredible… but what is it?

User Lifetime Value

The way I see it, good user experience does have a single unified purpose: maximizing customer lifetime value. From a present perspective, this is the expected profit generated by a customer by all of their actions over a period of time — the present value of their future cash (or, value) flows.

For web systems, we can just change customers to users.

And value in this approach doesn’t need to be revenue. It doesn’t even need to be in dollars. The principle holds for any of the many ways a user might contribute value to the system’s goals.

Lifetime Value (LTV) model

So, a probabilistic model for user lifetime value estimates the expected value of a user over a certain time horizon.

 E[LTV] = \sum\limits_{t=1}^T\frac{\pi _t  \rho _t}{(1+d)^t}  -  \sum\limits_{t=1}^T\frac{M _t}{(1+d)^t}  -  A

Where:

  • E[LTV] is the expected user lifetime value
  • for each period t from 1 to T
  • \pi _t are profits, or positive contributions from the user in period t
  • \rho _t is the probability of retaining the user in period t
  • M _t is the cost incurred for retaining the user in period t
  • A is the user acquisition cost
  • and (1+d)^t is the discount rate in period t

Ignoring the discounting, this amounts to a pretty simple model where user value can be manipulated in very specific and distinct ways. It pretty much tells us that expected LTV is a function of yearly profits times yearly retention rate, less yearly retention costs and an initial acquisition cost.

Implications for UX

What this comes down to is that there are a few areas of this equation where user experience can make a huge difference. Specifically, UX can manipulate parts of this equation to create more beneficial outcomes. That’s some serious power.

  • Retaining users (increasing that \rho _t) is the single best way to improve your expected user value over time. Luckily, this is the variable over which user experience has the most control. This is where delight may play a huge role.
  • Improving profits (increasing \pi _t) also has significant influence on LTV. Ex: streamlining the sales process, reducing barriers to contribution, increasing the value of contributions
  • Reducing acquisition costs (reducing A) Ex: streamlining the signup or registration process, increasing the probability of registration

This is how great user experience can deliver real value.

Just how influential is UX?

So, even if you buy the notion that a user’s present value can be estimated by a probabilistic model of their expected value flows, and even if you agree UX can influence those flows, the question remains — just how influential can it be?

The fact is that user experience is more important now than ever, partly due to the increasing buyer power in the information marketplace. With social networks, users have bigger voices, more influence, and more power. Their word-of-mouth effects are amplified by the number and nature of their connections.

Network Diffusion

We can think of these effects in terms of a simplified network diffusion model:

n\prime _t = (m  -  n _t)(\alpha  +  \beta n _t)

Where:

  • n\prime _t is the change in adopters in period t
  • m is the number of total potential adopters (network size)
  • n is the current number of adopters
  • \alpha is advertising influence
  • and \beta is word-of-mouth effects

You can see that word-of-mouth effects \beta play a significant role in the adoption of the system. Delight, joy, and all of the other squishy UX words are going to help make sure those powerful effects are positive.

Consider the alternative, where a negative or unfulfilling user experience so turns off a user that they take to their soapbox to warn others against joining your ranks. If you don’t like what users have to say, it’s gonna take a whole lot of advertising dollars to counter the effects of their two cents.

“No kidding, what people tell others about you is important.” Sure, but network diffusion allows us to perceive just how important it is. It implies that over time, even small changes in word-of-mouth effects can have exponential effects on system adoption reputation.

Network diffusion tells us that the purpose of UX is to make sure that when users talk, they’re laying the praise on thick.

Network diffusion vs user LTV

How does the network diffusion view (UX should aim to create positive word-of-mouth effects) compare or reconcile with the LTV view (UX should increase profits and retention rates, and reduce retention costs)?

Really, these ideas go hand in hand. Network diffusion is really an argument for how influential UX can be in the user LTV model — meaning, as users become increasingly connected, their effects on the variables of the LTV model are amplified. They have more sway, and their happiness is instrumental to any organization’s success.

Network effects are not explicitly captured in the LTV model, but you consider them baked into the existing variables. For instance, a user’s profit might include their own value plus that of any referrals that were made through diffusion. Same with retention rate — it increases for a user if their voice is actually creating new users.

Why does it all matter?

Creating a happy army

Happy users say positive things. They tell their friends positive things. They buy more; they stay around longer, they cost less to keep happy. They do all of the right things in all of the value models. They are so-called brand advocates — little footsoldiers of positivity that do work that would otherwise be very expensive for free. Making users happy is the closest thing we have to a silver bullet that automatically maximizes a user value projection.

As users continue to be better connected and more powerful in information networks, UX will have more and more influence over the variables in the lifetime value model. That makes the role of UX in addressing and exceeding user needs absolutely essential. The pressure is on to provide excellent experiences to users, with the viability of the underlying organization truly at stake.

What you do is… important?

Looking at user experience through the lens of expected user value tells us one thing for sure: it really does matter. To me, being able to quantify, estimate, and manipulate the way UX adds value to an organization is invaluable. It gives us a framework for articulating the value that’s otherwise just a fleeting notion in thin air.

I can finally hope to explain the first bit about what I do to friends, colleagues, employers. “Hey, you know that thing I do that doesn’t make a whole lot of sense to you guys? Turns out it’s actually really important; here’s how important.” They’re bound to get sick of this newfound smugness pretty quickly, but it will at least feel good the first few times.

There’s something incredibly satisfying about being able to articulate something in the perfect terms, and the user LTV model gives us a framework to help us do that for UX. I appreciate it, co-workers appreciate it, and certainly clients and employers appreciate it the most. Knowing the value of your craft gives you the ability to use your power for good, and the wherewithal to justify your worth.

Providing a plan of attack

Evaluating UX potential through user lifetime value doesn’t discount any of the traditional ways we like to measure UX. Do competitive analyses. Evaluate Neilsen heuristics. Research users, understand goals, map workflows, draw storyboards, develop personas. Build wireframes, iterate, iterate, iterate.

Do all of these things, just know why. Understanding your own user values can provide huge insights for the UX process:

  • Knowing the expected LTV of different customer groups or personas can guide the allocation of resources across those groups.
  • Identifying which LTV variables need improvement can guide the UX process to address different parts of the equation.

Because, at the end of the day I don’t want to design for the sake of designing or improve UX just to satisfy some ridiculous matrix.

I want to really understand where value can be added, then work the real magic.

How to make jQuery ajax (JSON) requests in WordPress

Overview & Preparation

Making jQuery ajax calls in WordPress to return JSON data to your client-side Javascript is an invaluable application that is only going to become more popular in the next few years. What’s the significance of using jQuery ajax to get JSON data from a WordPress site? Doing this (the right way) essentially allows you to request server-side information from your WordPress database, then have it returned to your client-side in one quick, extremely lightweight, and simple swoop. Ping the server, return the information you need. No page reload, no bulky parsing needed.

Luckily, there are some built-in utilities within WordPress that can be leveraged for this purpose.

Applications

Say you want to…

  • Populate a div with links to the 10 most recent posts after the page loads, or on a button click.
  • Allow the user to filter posts by tag, and return the results without reloading the page.
  • Load the comments for a post only if the user explicitly asks for them (clicks “show comments”, etc)

You get the point. Any time we want to get server data without reloading the page is a good application to use jQuery ajax to return JSON from the server.

The wrong (tempting) way

You might be familiar with using the jQuery.ajax() or jQuery.load() functions to return HTML data from other pages in your WordPress theme. However, using these functions to return bulky HTML data (as in when these functions return the contents of a particular div from a URL) when all you need is some text or an object to work with on the client side is an expensive process that requires lots of loading, rendering, and parsing.

To summarize:
Bad: Making ajax requests that ping arbitrary theme URLs, then parse and return bulky HTML data.

The right(er) way

Instead, we can get the necessary text or data structure from the server using JSON, which is much quicker, lightweight, and ultimately easier to work with on the client-side. Also, WordPress has a built-in utility to handle such requests, although developers often aren’t aware of it. Instead requesting the ajax data from another URL in the WordPress theme, we will pass the request to the file wp-admin/admin-ajax.php. This is a native file within WordPress whose job is specifically to handle such ajax requests and return lightweight results. All you’ll get back from this URL is your data, in JSON format. This way, you don’t have to parse through loads of HTML just to get the data you want.

Good: making ajax requests that ping WordPress’ built-in ajax utilities (wp-admin/admin-ajax.php) and return lightweight JSON data.

Requirements

To follow along with this completely you’ll need:

  • A jQuery-enabled WordPress site to play with. Anything 3.0+ will be fine
  • Google Chrome developer tools (makes this much more palatable)
  • Access to following 2 files:
    • wp-content/your-theme/functions.php (here we’ll add the handler functions for the server-side request).
    • wp-content/your-theme/js.js, or some other custom Javascript file to work with. Just make sure it’s loaded correctly in your theme so that the code will execute properly.

The data flow

Before getting started, let’s take a look at how our data is going to flow from beginning to end:

  1. User event on the client-side (button click)
  2. Javascript (js.js) click handler recognizes the click and initiates the jQuery ajax call.
  3. The jQuery ajax function makes a server side request at the URL that is given (remember, we will be using wp-admin/admin-ajax.php)
  4. The URL considers the request, and runs the appropriate function (this will be specified in functions.php)
  5. The function encodes the data to JSON format, then prints it out as its response
  6. The jQuery ajax function accepts this response as a Javascript object, and returns it to its success handler
  7. The success handler function (sub-function of the jQuery ajax function) uses the response data to perform an action on the client-side

The tutorial!

Security Considerations

I am not a security expert (ie, I’m sorry, but not responsible, if something undesirable happens to your site when you use a variant of this technique).

Most practical uses of admin-ajax.php provide an avenue for interacting with the WordPress database. However, there are a few simple things you can do to mitigate security concerns:

  • Pick secure names for your functions and “action” parameter (for simplicity, I use ‘do_ajax’ in this example; this could obviously be much more secure.)
  • Don’t provide methods for altering or deleting data in the hooked-in PHP function.
  • Validate all values passed to your PHP function to minimize the risk of injection.
  • If you don’t feel comfortable using admin-ajax, don’t use it.

That said, happy admin-ajaxing, and on to the good stuff.

Create a WordPress entry to interact with

First thing’s first; we’ll need an HTML document to interact with in order to attach this JSON-fetching process to a user event. You could also create your own HTML elements in a WordPress template, then create a new page and assign it your custom template — however, in the name of simplicity I’ll just create a regular WordPress post.

Go ahead and create a post; nothing too special. I’ll title mine “JSON Test.” I’ll also give it a unique a tag element that we can attach the click handler to; let’s call it

<a id="json_click_handler" href="#">
     Click here to do JSON request! We'll get the 10 most recent posts as JSON
</a>

One last thing: create a div that we can put the JSON results into once we process the request and get the results. I called it

<div id="json_response_box"></div>

Create the Post | How to do Jquery AJAX / JSON requests in WordPress

Step 1: Create the post

Create the the Javascript click handler in js.js.

In your custom Javascript file, make a click handler for the new link. Inside this click handler, we’ll put the AJAX request, and the response (success) function.

If you’re not familiar with jQuery.ajax(), read up here.

Here are the different components of our jQuery.ajax() call:

url
The url parameter should be set to the location of your admin-ajax.php file, which is part of the WordPress core within the wp-admin directory. So, the path should be www.yourwpdirectory.com/wp-admin/admin-ajax.php. This file exists specifically to process ajax requests like the one we are about to make!

dataType
This should be set to ‘JSON’, indicating that we want the data returned in JSON format.

data
The data parameter represents the array of REQUEST (GET;POST) parameters that are passed to the remote URL (admin-ajax.php). So, any value we enter under the data parameter of the ajax call will be available as a REQUEST variable in admin-ajax.php. For instance, if we pass

ourVar: 'someValue'

as part of the ajax data parameter, it will be available at the remote URL (admin-ajax.php) as

$_REQUEST['ourVar']

This is part of the magic of making jQuery ajax calls. for our purposes we’ll pass three parameters within data:

  • ‘action’:'do_ajax’ (the action parameter is REQUIRED BY WORDPRESS in order to tell the remote URL which function to hook into. It doesn’t have to be called ‘do_ajax’, but it does have to match the action hook we will write just a bit later. This way, whenever an AJAX request has an action parameter that matches our WordPress action hook, it will do the function that we specify in that hook.)
  • ‘fn’:'get_latest_posts’ (this will be used to tell admin-ajax.php which server-side function we want it to run, once the ‘do_ajax’ process has begun)
  • ‘count’: 10

This way, admin-ajax.php will have two REQUEST variables available during this call,

$_REQUEST['fn']

and

$_REQUEST['count']

success
In the success parameter, we specify a success function that will run if our AJAX request is successful. Let’s create this function, but leave it blank for now. Creating the success handler will be one of the last steps.

error
Similar to the success function, the error parameter specifies a function to run if there is an AJAX error. We shouldn’t get any errors, but if we do, it’s useful to know what’s going on here.

Here’s the complete click handler with jQuery ajax call, in js.js

jQuery(document).ready(function(){
     jQuery('#json_click_handler').click(function(){
          doAjaxRequest();
     });
});
function doAjaxRequest(){
     // here is where the request will happen
     jQuery.ajax({
          url: 'http://www.yourwpdirectory.com/wp-admin/admin-ajax.php',
          data:{
               'action':'do_ajax',
               'fn':'get_latest_posts',
               'count':10
               },
          dataType: 'JSON',
          success:function(data){
                 // our handler function will go here
                 // this part is very important!
                 // it's what happens with the JSON data 
                 // after it is fetched via AJAX!
                             },
          error: function(errorThrown){
               alert('error');
               console.log(errorThrown);
          }
          

     });

}

Test that the click handler and remote URL are working properly.

Open up the Chrome developer tools, and click the Network tab. This will show all of the network requests that happen, which will include the AJAX request we’ve just written.

Refresh everything, then go ahead and click the link you made at first in the ‘JSON test’ post, which now has the click handler attached to it.

Now, watch the network results. IF you’ve specified the correct location for the URL of admin-ajax.php, you will see a response like this:

Successful Ajax Call

Notice that the URL, admin-ajax.php, returns a Status code:200 OK. This is good, it means the the function is working, hitting the correct URL.

Also, notice that the key/value pairs that we specified in the jQuery.ajax() “data” parameter are now available at the remote URL as Query String Parameters. This is key, because it means we can use these values on the server-side.

Otherwise, if the URL isn’t right, you’ll see this:

Unsuccessful AJAX call

(You’ll also see the error alert that we wrote as the error response to our jQuery.ajax() function).

If you don’t see any such AJAX requests being processed when you click the button, then your click handler, or resulting AJAX function has not been attached properly.

Hopefully, you saw case #1, a successful AJAX request. If so, we can move on to setting what happens once admin-ajax.php receives this request!

Add action hooks to functions.php to sync the client- and server-side AJAX mechanisms, and start making a server-side (PHP) handler function

Now that the client-side jQuery.ajax() call is successfully sending the AJAX request to admin-ajax.php, it’s time to determine what happens with this data once the remote URL is hit.

Even though the action is happening at admin-ajax.php, we don’t have to edit this file at all. Instead, open up functions.php from within your WordPress theme, and we will write functions that hook into actions on admin-ajax.php from here. This way, we’re not messing with any source code; just hooking into it from within our own theme.

We need to add 3 components to functions.php:

  • 2 actions hooks that tell admin-ajax.php to run a certain function, depending on the ‘action’ parameter that the AJAX request sends.
  • The resulting function to run

So, the code should look like this:

add_action('wp_ajax_nopriv_do_ajax', 'our_ajax_function');
add_action('wp_ajax_do_ajax', 'our_ajax_function');
function our_ajax_function(){
     // now we'll write what the server should do with our request here
}

Notice that the suffix of the ‘wp_ajax_nopriv_’ and ‘wp_ajax_’ action hooks match the action parameter sent from the jQuery.ajax() call, which was ‘do_ajax’.

This means whenever admin-ajax.php receives an AJAX call, it will see what the ‘action’ parameter is. If the ‘action’ parameter is set to ‘do_ajax’, it will run ‘our_ajax_function’. Sounds good!

Build the PHP handler function

We just started building the AJAX request handler function, ‘our_ajax_function’. Now, let’s add to it and make it actually work.

Before getting started, let me explain my philosophy about this function. I recommend making ‘our_ajax_function’ into a mini AJAX switchboard that handles all AJAX calls — because, although we only have one ajax call now, we might have any number in the future. In other words, doing it this way scales well. Then, this switchboard can check the accompanying parameter ‘fn’, and invoke specific functions according to the value of that argument.

Why don’t we just use the ‘action’ parameter to determine which function to run, isn’t that what it’s for? Sort of, yes. But that means you’d have to write a WordPress action hook for every single AJAX function you wanted to run; that’s a pain. Instead, I like to send every AJAX call to the switchboard function, ‘our_ajax_function,’ by setting ‘action’:'do_ajax’ in the jQuery.ajax() call. Then, we can call more specific functions depending on what value is passed for the ‘fn’ parameter.

So, in functions.php

function our_ajax_function(){

   // the first part is a SWTICHBOARD that fires specific functions
   // according to the value of Query Var 'fn'

     switch($_REQUEST['fn']){
          case 'get_latest_posts':
               $output = ajax_get_latest_posts($_REQUEST['count']);
          break;
          default:
              $output = 'No function specified, check your jQuery.ajax() call';
          break;

     }

   // at this point, $output contains some sort of valuable data!
   // Now, convert $output to JSON and echo it to the browser 
   // That way, we can recapture it with jQuery and run our success function

          $output=json_encode($output);
	     if(is_array($output)){
		print_r($output);	
	     }
	     else{
		echo $output;
	     }
	     die;

}

As you can see, this switchboard is now going to call one more function, ‘ajax_get_latest_posts’, because the ‘fn’ parameter of our jQuery.ajax() call matches the first case on the switch statement. So, we need to make this specific function, ‘ajax_get_latest_posts’, to, well, get the latest posts, and return the results as an array of PHP objects. So, also in functions.php

function ajax_get_latest_posts($count){
     $posts = get_posts('numberposts='.$count);
     return $posts;
}

So, running through the PHP code in ‘our_ajax_function’, this is what happens:

  • The switch statement starts, checking the value of $_REQUEST['fn']
  • The first check is true, $_REQUEST['fn'] == ‘get_latest_posts’, so the first case will fire
  • ajax_get_latest_posts($_REQUEST['count']); runs, and returns an array of the latest 10 posts.
  • Back in function ‘our_ajax_function’, $output now == the result of ajax_get_latest_posts. So, $output is an array of the 10 latest posts.
  • To conclude ‘our_ajax_function’, the value of $output is converted to JSON via PHP’s json_encode method, and echoed, in order for the original jQuery function to access it.

Where are we now? We’re back to the success function of the jQuery.ajax() function, and the “data” argument contains the server-side output. In other words, “data” in our jQuery.ajax() success function now holds the contents of what was just $output in our PHP function.

That was the magic. Now let’s DO something with that response.

How to detect Enter keypress with Javascript / jQuery

The problem

As I’m sure you know, Javascript has a nice event called keypress that detects the client-side press of a key from the keyboard. However, there are times when you need to get more specific than that and detect the press of a particular key. Of course — at least in my experience — that key is usually Enter.

By expanding upon Javascript’s innate keypress event, we can write a function to easily detect the specific press of the Enter key. There are 2 different ways we can do this:

  1. Write a function to detect the Enter press, then simply return true or false. Then, use this result to either do a resulting action or not.
  2. Write a function to both detect the Enter press, then run a subsequent function if Enter press is detected

Solution 1: Write a function to detect the Enter press, then simply return the result

The first solution is to write a function that simply interprets the keypress, decides whether or not the keypress is an Enter press, then returns the result — either true or false. Then, you can use this function as a check in other functions — that is, you can determine if Enter has been pressed, and, if so, run the other function. In these examples, we’ll call our checking function returnEnterPress();, and the result functionendResultFunction();.

Let’s start with the checking function returnEnterPress();. It should look something like this:

function returnEnterPress(e){
    var keynum; // set the variable that will hold the number of the key that has been pressed.
    
    //now, set keynum = the keystroke that we determined just happened...
    if(window.event) // (IE)
    {keynum = e.keyCode;}

    else if(e.which) // (other browsers)
    {keynum = e.which;}

    else{ // something funky is happening and no keycode can be determined...
        alert('nothing found');
        keynum = 0;
    }

    // now that keynum is set, interpret keynum
    if(keynum == 13){ // this is Enter (keyascii code 13)
        return true;
    }
    else{ // this is something other than enter
        return false;
    }
}

Now, let’s set up a handler to run this checking function, determine whether or not Enter was pressed, and, if so, run the ultimate function endResultFunction();. You can attach this handler to whatever element you want — but in this example, we’re going to attach the handler to the entire document’s keypress event with jQuery:

jQuery(document).keyup(function(e){
    var enterPress = returnEnterPress(e); // set this variable equal to the result of the function we just made. So, if that function returns true, the variable enterPress will be true as well.
    if(enterPress){ // Enter has been pressed. Let's run the ultimate function
        endResultFunction();
    }
});

endResultFunction(); can be whatever function you want to ultimately run, given that Enter has been pressed. Go ahead — try it. Hit enter anywhere on this page, and your keystroke will go through the exact process outlined above — ultimately ending up running my endResultFunction(), which simply prints an alert.

Solution 2: Write a function to both detect the Enter press, then run a subsequent function if Enter press is detected

While solution 1 gets the job done, I prefer this second solution for most applications. In solution 1, we wrote a detecting function, then used it in a handler as a gateway to the end-result function. However, with solution 2, we can combine the 2 parts, so that both the detecting of the Enter press and running an end-result function happens all in one step.

Let’s write the function to do this. Then, we’ll attach that function to a keypress event:

function runFunctionIfEnter(e, fnName){ // the arguments here are the event (needed to detect which key is pressed), and the name of the resulting function to run if Enter has been pressed.
    
    var keynum; // establish variable to contain the value of the key that was pressed

        // now, set that variable equal to the key that was pressed
       
         if(window.event) // ID
        { keynum = e.keyCode;}
        else if(e.which) // other browsers
        { keynum = e.which;}

        if(keynum == 13){  // if the key that was pressed was Enter (ascii code 13)
            eval(fnName)(); // run the resulting function name that was specified as an argument
        }
}

Nifty, eh? Now we just need to attach this function to an event, so it will be fired when we want it to. Again, you can attach this to whatever event you want, but I’m going to attach it to the document keypress using jQuery:

jQuery(document).keypress(function(e){
    runFunctionIfEnter(e, 'endResultFunction');
});

With this solution, endResultFunction(); will be called every time runFunctionIfEnter() determines that they keypress event it handles was an Enter keypress. This solution is a more efficient application if you are always going to use the Enter check to determine whether or not to run a resulting function. That’s what I normally use Enter checks for, so it’s the solution I generally prefer to go with.

How to create your own shortcode in WordPress

What is a shortcode?

If you’re a WordPress user, chances are you’ve come across plugins that use shortcodes. What are shortcodes? They’re the little pseudo-code snippets, enclosed in brackets, that can be used in the post content section of the WordPress backend post editor. [shortcode], for example.

For example, two of the most popular WordPress plugins I use make use of shortcodes. Contact Form 7 uses shortcodes like this: [ contact-form 1 "Contact form 1" ] to display contact forms within the post content. NextGen Gallery also uses shortcodes like this: [ nggallery id=x ] to display photo galleries within the post.

Essentially, a shortcode is a snippet that tells WordPress to replace itself with a particular function of code that does something. By making your own shortcodes, you get to decide what that snippet is, and what it’s functionality will be. Believe it or not, WordPress makes this process pretty simple.

Anatomy of a shortcode

As defined in WordPress’ shortcode API, a shortcode has 3 essential pieces:

  1. The shortcode name ([shortcode_name])
  2. Attributes ([shortcode_name att1="a" att2="b"])
  3. Content ([shortcode_name]Content here[/shortcode_name])

As you can see in the example above, shortcode attributes and content are two separate ways to pass information to a shortcode’s handler function. Your shortcode can have neither attributes nor content, either one or the other, or both — it’s up to you. Likewise, it can be either enclosing (as in the content example above) or self-closing (as in the attributes example). Self-closing shortcodes may only pass attributes to the handler function, as they don’t surround any content. Which combination of shortcode anatomies you want to use is completely up to you.

How to create your own shortcode

Creating your own WordPress shortcode can be essentially done in 5 easy steps:

  1. Decide which type & configuration of shortcode you want to use
  2. Select the shortcode name you want to use, and the names of any attributes.
  3. Create a test case to work with in a sample post
  4. Create a handler function for this shortcode
  5. Assign the handler function to the shortcode tag

Let’s go through each of the steps.

Step 1: Decide which type of shortcode to use

In this first step, consider which of the shortcode anatomies (outlined above) to use. At the very minimum, your shortcode will be a self-enclosing shortcode with a name ([shortcode_name]). This alone is sufficient in some cases (for instance, replacing occurences of that shortcode with the results of an independent function).

However, if you need to make your output more dynamic, you might consider giving your shortcode attributes, and/or making it an “enclosing” shortcode that encapsulates a bit of content. In these cases, both the attribute values and enclosed content will be passed to the handler function, in order to produce more dynamic results (ie, [shortcode_name att1="a"]some content[/shortcode_name]).

Select a shortcode configuration that best suits your functionality’s needs.

Step 2: Select your shortcode and attribute names

Next, you need to select a shortcode name that will define this shortcode. For example, when you use this shortcode in the wild, you will refer to it as [shortcode_name]. From here on out, I’ll call mine “include”, such that the resulting shortcode will appear like [include].

At this stage, you should also decide what to name your shortcode’s attributes (if you’ll be using any). I’ll use “id”, “height”, and “width” as my attributes, which can be used along with my shortcode like this: [include id="1" width="100" height="50"]

Once you’ve decided about your shortcode’s name and attributes, we’re ready to create a test case to start working with.

Step 3: Create a test case to work with in a sample post

Yes, this step is as easy as it sounds. Simply go into your WordPress admin dashboard and create a new sample post. Now, somewhere within your post content, include the new shortcode that you just made up. I’ll write [include id="1" width="100" height="50"]test content here[/include] in mine. Either publish the post, or, if you’re working on a live site, you might just want to save it as a draft. Then, click “Preview” or “View post” in order to see the post’s output.

Nothing special here. Since we haven’t created a handler for the shortcode yet, it’s nothing more than a bit of text on the page. However, all that’s about to change…

Step 4: Create a handler function for this shortcode

This is the step where we bring our shortcode to life.

Open up your theme’s functions.php file; this is where we’ll add our handler function. I’ll call mine include_shortcode_handler($atts=null, $content=null){}, but you can name yours anything you want.

You’ll notice that our function takes 2 parameters: $atts and $content. I initialize both of these values to null, just in case a shortcode doesn’t pass one of these values to the function. For standard purposes, though, every time I use my shortcode like I did in the test case ([include id="1" width="100" height="50"]test content here[/include]), $atts and $content will both receive values in the handler function, because the shortcode contains both attributes and content.

Now in the handler function, you can do all sorts of cool stuff that I won’t get into, only because it’s not unique to shortcodes. For example though, you can create a whole bunch of dynamic output, according to the values that the function receives from $atts and $content.

However, the one thing that is particular to shortcode handler functions is that the result of the function must be the returning of a particular value. For example, at the end of the function, include a line like return $some_variable;, where $some_variable contains the value that you want to replace your shortcode with in the post content.

Step 5: Assign the handler function to the shortcode tag.

At this point we’re almost done. We’ve created the shortcode, and entered it into a WordPress post as a test case. In the backend, we’ve created a handler function in our functions.php file. The only step left is to link the two, and let the magic happen.

To assign the handler function to the shortcode, we have to use the WordPress function add_shortcode(). This function takes 2 arguments: the first is the shortcode name, and the second is the handler function name. So, for the example I created, the correct syntax would be add_shortcode('include', 'include_handler_function');.

All you need to do is save that one function call anywhere in your functions.php file, and we’re good to go.

Check it out!

Now that we have everything taken care of, accounted for, and linked up, we can test our shortcode to make sure it’s working correctly. Simply refresh the preview of the post where we used the shortcode in the first place, and it should be replaced with the result of the function it is now linked to. For example, if my handler function was set to return 'hello!';, all instances of my original shortcode should be replaced with the phrase “hello!” in the rendered page.

How to see all of an object’s properties in Javascript

The problem

Sometimes while working on a project (especially on a team where you are constantly interacting with other peoples’ code) you may encounter objects in Javascript whose properties you need to refer to and access — but you aren’t sure what properties the object has in the first place. This frustrating problem can slow down the development process — but worse, your Javascript can quickly become polluted with redundant variables and logic if you write new functions to accomplish what the object’s unknown properties may already do.

Learning Javascript on my own, I can think back on many times where I made this mistake and “re-invented the wheel”, so to speak, when I could have just used the values of existing object properties to accomplish what I needed. Well, by using the following tactics, you’ll never have to take that messy, time-consuming workaround again. These are just my 2 favorite ways to find the unknown properties of an object in Javascript — they may or may not be the most efficient ways to accomplish this, but they’ve worked great for my purposes.

The solution

In my experience, I’ve used 2 methods to solve this problem. Let’s start with the best.

Firebug Console

Printing the object to the Firebug console is definitely my favorite way to observe its properties — however, the caveat is that you need Firebug to accomplish this (and therefore, Firefox). If you can swing it, though, I would definitely recommend this method.

  1. Put this code snippet in your Javascript file at the point where you want object to be logged, just as you would an alert: console.debug(objName);
  2. Load the page in Firefox, with Firebug open.
  3. Click on the console tab
  4. Proceed through your page, triggering whatever events are necessary until the object is encountered
  5. Check out the results in the console!

Slick eh? The one annoyance about this method is that this code will throw a Javascript error if you load the page in a browser other than Firefox, or even in Firefox without Firebug open. So, when you’re done examining the object, be sure to comment this line out.

Javascript Alert

If you’re not in Firefox (how do you stay sane developing for the web?), or you’re in Firefox without Firebug (again… how?!), this method will accomplish the same thing, albeit slightly less elegantly. I say “less elegantly” because 1) the resulting alert interrupts your normal browsing (ie, causes your page to perform differently than it would without it), and 2) the alert method isn’t the ideal way to print the properties of a very long object. If your object is long enough (that's what she said... too easy...), or you are iterating through multiple objects, the resulting string can end up being too big to fit in the alert box, and therefore run off the bottom of the page. For most intents and purposes though, this method gets the job done well enough.

  1. Put this code snippet in your Javascript file, where you want the object to be alerted: alert(data.toSource());
  2. Load your page in a browser.
  3. Proceed through your page, triggering whatever events are necessary until the object is encountered
  4. Check out the results in the alert!

That’s It!

I hope these tricks will help you easily identify the unknown properties of objects in your Javascript projects — they sure have helped me. Do you know of any even better solutions to this problem?

Removing annoying <link> tags from the WordPress header in WordPress 3.0

The Problem

One of the great things about WordPress is its simplicity and cleanliness. So, it only makes sense that one of the things that annoys me about the platform is the array of seemingly useless <link> tags that are output in the <head> section of the site by the function wp_head().

Sure, leaving these tags in might make sense to some users. On the other hand, some have claimed that leaving these tags in place can be detrimental for SEO purposes.

I don’t have an opinion one way or the other on this point. I’m not necessarily saying that these <link> tags should be removed. It’s just that I can see no use for them in my purposes, so I’d rather get rid of them. Less clutter, more clarity, fewer broken links showing up in my reports, and cleaner markup.

The solution

Sure, we could go hacking through the core to find the calls that generate these link tags, and edit them out. However, it’s usually best to stay out of the core files, since edits to the core are overwritten (and therefore need to be re-created) on each upgrade.

Instead, the scalable solution to this problem comes in the form of WordPress’ remove_action() function.

This solution is simple, scalable, and elegant. Simply include the appropriate remove_action() declarations at the top of your functions.php file, and you’ll get rid of these pesky tags for many versions to come.

NOTE: It’s important to mention that some of the following function names are new to WordPress 3.0, so be sure to use the examples below for the most up-to-date implementation!

Here is what I put in my functions.php file in order to get rid of the pesky <link> tags:

remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
//remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'start_post_rel_link');
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
remove_action( 'wp_head', 'feed_links_extra', 3 ); // Display the links to the extra feeds such as category feeds
remove_action( 'wp_head', 'feed_links', 2 ); // Display the links to the general feeds: Post and Comment Feed
remove_action( 'wp_head', 'parent_post_rel_link'); // prev link
remove_action('wp_head', 'rel_canonical');
remove_action( 'wp_head', 'wp_shortlink_wp_head');

You can see I commented out the line that would remove the tag that shows the version of WordPress, since I decided I kind of like that printed in the <head> section. (WordPress tends to be a good platform for SEO, and blatantly broadcasting that you’re using it can’t hurt…). But other than that, these few lines of code get rid of all the annoying <link> tags that clutter up the default headers in WordPress 3.0.

Counting the number of posts with a given tag in WordPress

Problem

So, on my new WordPress blog (you’re on it!) I’m going to be using post tags to classify and describe each blog post. That way, I can then use these tags to organize blog posts by tags (which will be topics), and even create a navigation feature to direct readers to tag archive pages (to your right! — I know, this is all too convenient).

Anyway, I was thinking, wouldn’t it be cool to give users a clue about what type of content they were getting themselves into, before they clicked to go to a tag archive page? That is — can we at least provide a tally of how many posts a user can expect to find under a given tag classification?

C’mon, of course we can!

The Solution

Since I want to use this function on a normal blog post page (derived from template file “single.php”), we have to first get a list of the tags we want to find the tally for. Let’s do this first with function get_the_tags();.

This function returns an array of tags associated with the current page. So, let’s set the function equal to a variable, $posttags.

$posttags = get_the_tags();

Ok. Now that we’ve captured an array of the current post’s tags, let’s loop through $posttags and figure out how many posts are living under the classification of each post tag. We’ll do this with the function get_posts();(all available parameters are also listed at the bottom of that page) This function allows us to get an array of all the posts that match the parameters that are passed to the function. We could pass any parameters to get_posts(), and we would get an array of all matching posts in return. But since we want get the number of posts with a given tag, let’s simply query by that post tag, using the ‘tag=tagslug’ parameter. Check it out below.

// get an array of all tags associated with this post.
 $posttags = get_the_tags();

 if ($posttags) { //if any are found...
      foreach($posttags as $tag) { // loop through each...
		     
      // get an array of all posts that have this tag slug...				  
      $result = get_posts('tag='.$tag->slug);

...

Great. Now we have a variable $result that contains an array of all posts that matched the query we executed with get_posts(); Thus, $result should hold all posts that have been classified under the current tag in the foreach loop.

Now, we can do anything we want with this array of posts. But all we wanted to do was count how many posts have been given each post tag, and this is going to allow us to do just that. by using the php function count() on our $result variable, we will be able to know exactly how many posts are in this given tag taxonomy.

Final Solution

 // get an array of all tags associated with this post.
 $posttags = get_the_tags();

 if ($posttags) { //if any are found...
         foreach($posttags as $tag) { // loop through each...
		  
         // get an array of all posts that have this tag slug...				  
         $result = get_posts('tag='.$tag->slug);
			
          // print out the post count for each tag			 
          echo 'There are '.count($result).' posts classified under the '.$tag->name.' tag.
'; } //end foreach loop } // end if posttags

Fixing Scriptaculous autocompleter up/down scrolling behavior

The Problem

One of the projects I’m working on is using a lot of client-side functionality — such that we’re mixing and matching libraries to achieve the functionality that we need. I explain this to defend the fact that we’re still using Scriptaculous’ autocompleter in the first place — whereas the rest of the client-side is build in jQuery and jQueryUI. For our purposes it just seems that the Scriptaculous autocompleter is easier to use with autocomplete lists produced by ajax on the fly, via DWR. Please correct me if I’m wrong about this, because I’d love to switch over to the jQueryUI autocompleter altogether. However, it just doesn’t seem to be as good a fit.

Here’s how we’re handling the autocompleter with Scriptaculous and DWR:

new Autocompleter.DWR('searchStringField', 'idToBeFilledWithSuggestions', updateFunction,{ valueSelector: nameValueSelector, partialChars: 0 });

That said, there is a functional/end-user problem with Scriptaculous’ autocompleter that you don’t seem to find with jQueryUI’s. Specifically, when you scroll through the autocompleter list with the up and down arrow keys, Scriptaculous’ autocompleter behaves rather annoyingly. Rather than just cycle through the items in place, the entire page “jumps” as you press the keys. For example, when you cycle up with the up arrow key, the page jumps so that the list item is positioned at the top of the browser window. When you cycle down, the opposite happens.

Check out an example that another frustrated developer created here »

Proposed Solutions

With a little research, I tracked down the problem to a few lines of the Scriptaculous file “controls.js”, as documented in this Scriptaculous ticket.

Now, there are a few solutions proposed here.

  1. The first is to simply comment out the offending lines of code in the file controls.js.
  2. The second is to apply a patch to resolve the issue

Final Resolution

Well, with my limited knowledge of Prototype and Scriptaculous, I simply opted for solution #1 — that is, commenting out the lines of code that seem to produce this undesired behavior. For what it’s worth, I’m using controls.js version 1.8.2, © 2008. So, in my file, the offending lines of code are 216 and 222. Simply commenting these lines out solves this jumping issue completely.

Now, take this solution with a grain of salt. Since I don’t depend heavily on Prototype or Scriptaculous throughout the rest of this project, I have no problem removing this functionality from the core completely. However, if you rely on lots of Scriptaculous functionality on your site, this may solve the jumping issue, but break something else. However, for those who are using Scriptaculous exclusively for its autocompleter, I see no real issue (thus far) with solving the problem via this little hack.

Thanks to user Mike Boone for tracking down this issue and finding the offending lines of code.