Posts Tagged “WordPress”

Change the default avatar in WordPress

by clark. 0 Comments

If you’ve ever wanted to change the default avatar in WordPress, all you need is a quick filter in functions.php that inserts and names your new avatar. Once you add the markup below, you’ll see your new avatar type listed in wp-admin > Settings > Discussion along with the choices like Identicons and MonsterID. The code:

<?php 
add_filter( 'avatar_defaults', 'newavatar' );  
function newavatar ($avatar_defaults) {  
$myavatar = get_bloginfo('template_directory') . '/images/avatar.png';  
$avatar_defaults[$myavatar] = "Pigs";  
return $avatar_defaults; } ?>

This is a pretty simple one. Our function newavatar() is hooked to the avatar_defaults, and we simply add our new avatar choice, which includes a path to the image URL along with a title (pigs!). At the end, we return the defaults, which has been impregnated with our new custom avatar, and no one is ever the wiser!

WordPress comment hacks: User-only comments, restrict by user age and more

by clark. 0 Comments

In a recent promo for Android and Me, we created a bunch of giveaways, each with a specific limitation on entry. We had 25 days worth of prizes, and each day held a different challenge. We used comments as the main way to enter, and on certain days we wanted to restrict entry to certain groups of users.

Some days we only wanted users who had added their Twitter account to the profile (a piece of user meta), some days we wanted only members of a certain age to be eligible (a piece of user meta compared to a set value), and overall, we wanted all comments to be from registered users only (private comments on certain WordPress posts).

To accomplish all these things, I came up with the simple hack of creating a slew of conditional checks that surround comment_form(). If you’re not familiar, it’s a function that outputs the comment form itself and is usually found near the bottom of comments.php. It’s a pretty easy way to control who is commenting, taking away the form. Take a peek a the heavily commented code below (no pun intended) and join me after for some play by play.

<?php 
//start by checking for a couple of key pieces of info
$current_user = wp_get_current_user();
$private_comments = get_post_meta($post->ID, 'private_comments', true);
$meta_lock = get_post_meta($post->ID, 'meta_lock', true);
$time_lock = get_post_meta($post->ID, 'time_lock', true);

//if the post has the custom field 'meta_lock'
if ($meta_lock) {
  //check the current user for that meta field
  $user_meta_key =  get_user_meta($current_user->ID, $meta_lock, true);
    if ($current_user->ID AND $user_meta_key) {
      //display the comment form
      comment_form();
      //give an error message (add some flare!)
    } else { echo 'Special users only!'; }

//if the post has the custom field 'time_lock'	
} elseif ($time_lock) {
  //get the age of the user and prepare the age limits
  $user_age=date("Y-m-d", strtotime($current_user->user_registered));
  $age_limit = strtotime($time_lock);
  $account_age = strtotime($user_age);
  
  //if the current user is OLDER than the set limit
  if ($current_user->ID AND $account_age <= $age_limit) {
    //display the comment form
    comment_form();
  //give an error message (add some flare!)
  } else { echo 'Users older than '.$tegra_time.' only!'; }

//if the post has the field 'private_comments'	
} elseif ($private_comments) {
  //check if the user has an ID (aka is signed in)
  if ( $current_user->ID ) {
    //display the comment form
    comment_form();
  //give an error message (add some flare!)
  } else { echo 'Users only!'; }

//no special conditions met, just display the comment form  
} else { comment_form(); } ?>

Jeeeez that's a scary wall of text! Ok, not really, but compared to just the single line comment_form() we started with it looks pretty major. What we're doing is actually pretty simple. Anytime the template would normally call comment_form, we're getting in the way and checking some settings first.

What settings? Things we set on a post per post (or page) basis, using custom fields. If you'd like to turn on user-only comments, set a custom field 'private_comments' with any value (I usually just go with 'true'). If you'd like to restrict comments based on whether or not a user has a certain meta field, on your post set a custom field with the key 'meta_lock' and a value matching whatever user meta you'd like to filter by. This can be a user's real name, website link, bio, etc. It's a great way to push your users to fill out certain fields of their profile.

One of the funnest challenges we did was based on user age, something you'll see in the snippet above as age_lock. To use it, simply set a custom field on your post with a YYYY-MM-DD format (one year before today's date, for example). When comments.php is rendered, it'll compare the date the user registered with the date you've entered in the field 'age_lock'.

These few examples are really just to get the juices flowing, and to introduce you to the simple hack of conditionally displaying the comment form. There are an infinite number of things you could check or compare, so if you explore and find something killer make sure you come back and share it with us.

So far, I think my favorite use of this technique was tracking user tweets with the service Rowfeeder, which I then used to export a full list of Twitter usernames. Since our accounts let users link their Twitter handle, I was able to check which WordPress accounts had successfully Tweeted and then conditionally allow them to comment. Total score!

Sort WordPress users by custom meta value with get_users

by clark. 0 Comments

I’ll be honest. This one took me a while. I spent a lot of time looking for a solution but there doesn’t seem to be a whole bunch of discussion around user queries in plain ol’ WordPress. I guess most of the big user action has moved on to bbPress and BuddyPress.

For those of us with a sizable user base contained only inside WordPress however, actually doing things with users takes a bit of elbow grease. I’m sure all the same possibilities exist, but people don’t seem to talk or write about them as often, which is where this guide comes in.

Today we’re going to look at getting WordPress to sort users by a custom meta value, something that would be useful if your users have any sort of scores, totals, or custom profile fields.

Over on Android and Me, all users have a point total. We then rank all users by that point total and assign everyone a percentile rank. To call up thousands of users based on a custom meta value seemed daunting, and it was, until I got a bit more familiar with WP_User_Query.

WP_User_Query was introduced in WordPress 3.1 and brings us an easy and flexible way to query our user database. We’ll be using the function get_users, which is basically a wrapper for WP_User_Query. You’ll notice the function includes an ‘orderby’ parameter, but the only options given are:

orderby – Sort by ‘nicename’, ‘email’, ‘url’, ‘registered’, ‘display_name’, or ‘post_count’.

Notice we’re missing ‘meta_key’ or ‘meta_value’, so we’re on our own when it comes to ordering these guys by a custom field. Also of note is ‘post_count’, which I could totally see coming in handy on certain community blogs (MAKE A NOTE!). Now that we know what we’re after and what tools we’ll need to make it happen, it’s time we get started.

The Code

<?php 
//these are the arguments for the get_users function below
$args  = array(
  'fields' => 'all_with_meta',
  'meta_query' => array(
    array(
    'key' => 'points', // the meta field (or key) we want to target
    'value' => '2',    // the value we want to target (optional)
    'compare' => '>='  // comparison method (optional:  =, >, <, etc)
    )
));

//get_users calls WP_User_Query and returns an array of matching users
$users = get_users($args;)

//custom function for comparing the data we want to sort by
function cmp($a, $b){
  if ($a->points == $b->points) {
    return 0;
  }
  return ($a->points > $b->points) ? -1 : 1;
}

//usort sorts our $users array with our function cmp()
usort($users, 'cmp');

//leaving an array of $users sorted by the value of meta 'points'
foreach ($users as $user) {  
  // do something rad!
} ?>

I've commented the code above so hopefully you were able to follow along in the actual markup, but if you'd like a short summary: here we go!

I start off with a short list of arguments, or options, that get_users() needs to return the users I want. A full list of parameters can be found on the get_users page in the Codex. The key here is meta_query, which lets me specify the user meta field I'd like to target and compare. I so happen to be calling up users based on their point totals, so I call any user with points above or equal to 2 (any below that I can assume is a scrub and just rank at the bottom of the pile to save some query juice).

Once I've got my $args, I go ahead and run get_users($args). Doing so will return a full list of users that match the arguments, all handily stored in the array $users.

But what's that? They aren't sorted? While we were allowed to compare points while calling the users, no actual sorting took place. This is where we get a bit tricky. Instead of relying on WordPress to sort the users for us, something the Codex says isn't possible right now, we're going to bust out PHP's usort along with a simple custom function for comparing the points.

Our custom function, cmp(), is just a little check that runs that compares the point total of a user with the other point totals in the array. If the totals are the same, the function returns '0'. If they are different, the function returns a '1' or '-1'. That simple math is enough to let usort crunch through thousands of users in seconds, something I'd spent a couple weeks trying to figure out how to make WordPress do for me. Oh well, you know how that goes.

Now that we've got $users in order by the meta field 'points', all that's left is to do something rad. Simply use a foreach (PHP's version of The Loop) to run through the users in the array and accomplish something. In my case, it was doing even a bit more math to calculate each user's percentile in order to show what everyone's point totals really meant in relation to one another.

I know not everyone's blog has a point system, but if you've got any amount of users or even multiple authors this might come in handy. I used WP_User_Query all over the place on the WordUp Austin site. On Android and Me, I list the author pictures in the sidebar. Now, if I wanted to, I could order them by post count or point totals.

Slowly but surely I'm accumulating bits of community-focused solutions like this one and soon I'll be able to say with complete certainty that my WordPress install would slay any bbPress or BuddyPress install you can toss at it.

Intelligent caching of changing data with the WordPress Transients API

by clark. 2 Comments

Recently I built a shortcode for displaying data from the Android Market. You can see it in action on Android and Me. To make the magic happen, I query the AppAware API for a couple key bits of data, mainly the app icon, title, developer name, etc.

After a while, I realized that even without a rate limit being imposed by AppAware, some of my calls were failing. To lighten the load, I turned to the WordPress Transients API, a super simple way of saving (or caching) data for later use. Because saving a transient stores the data locally, you won’t need to make as many external calls, which is good for you and for your API partners.

What is the Transients API?

If you’re an experienced developer and you’re familiar with the concept of caching, you can probably skip this section. The code samples are below. But if you don’t know a thing about saving data locally, WordPress says: the Transients API offers a simple and standardized way of storing cached data in the database temporarily by giving it a custom name and a timeframe after which it will expire and be deleted. Also of note is that Transients are inherently sped up by caching plugins, where normal options are not.

For this reason, transients should be used to store any data that is expected to expire, or which can expire at any time. Transients should also never be assumed to be in the database, since they may not be stored there at all.

This makes transients the perfect solution to storing data you would otherwise call from a 3rd party. Ideally, when you need the data, you’ll first check to see if the transient exists. If it does, you use that data. If it doesn’t, you call for a fresh version of that data, when you then not only use, but save and timestamp for later use. Sound simple enough?

Setting and getting transients

The main functions we’ll be using are, predictably, set_transient and get_transient, both of which couldn’t be simpler. To get started, let’s look at the absolute first step, saving a transient. If you’ve ever saved meta data using update_post_meta or update_user_meta, this should look totally familiar to you.

<?php set_transient( $transient, $value, $expiration ); ?>

The function accepts three arguments, all of which are pretty straight forward. First, $transient is the name of the actual piece of data to be stored. This is the unique ID by which you'll call the data later, so make it good. The $value is the actual data being stored, aka the payload. You'll use $expiration to set the time limit on this transient, in seconds. When the time expires, so does the data.

Once you've got some data saved, you'll likely want to call it in your templates. Getting a transient is even easier than setting it:

<?php get_transient( $transient ); ?>

Here, again, $transient is the unique identifier of the data your looking for. There isn't much to explain here. When you call the transient, if the time limit hasn't expired, you'll have the data to do as you please. If the data has expired and you still need it, things get a tiny bit more complex, which brings us to my next point...

Putting it all together

Our sample case will be displaying our Klout score, via the Klout API. Like I said, this Transients API should be used for time-sensitive data, data that changes or that needs to be refreshed at a reliable interval. And while we're discussing use, it doesn't have to be external data, you could use it to store just about anything. We're just going the API route during the example to score some bonus points.

I've heavily commented the code below, but the basic path goes like this. First, we'll attempt to call the transient. If the data exists, our job is done and we use it. If the data doesn't exist or has expired, we'll call for a fresh copy from the Klout API, which we'll then save and immediately use.

The entire process is basically an if statement that uses both set_transient and get_transient.

<?php //let's get my klout score!!

//first, let's see if I've got the data already cached locally
$klout = get_transient("klout"); 
  
  //dang it! it looks like I might not. let's check with the Klout API
  if( !$klout ) {  
    $json = file_get_contents("http://api.klout.com/1/klout.json?key=[API key]&users=clarklab");
    $return = json_decode($json, true);
    $kloutscore = $return["users"][0]["kscore"]; 

    //if the Klout API gave us a score, let's save it!
    if( $kloutscore ) {
      
      //in a field named "klout", we'll save our $kloutscore, for 12 hours (60 seconds x 60 minutes x 12 hours)
      set_transient("klout", $kloutscore, 60 * 60 * 12);

      //let's also make sure to set the data you were originally looking for
      $klout = $kloutscore;  
    }  
  }
	
echo 'Now I can safely check my '.$klout.' score with transients!'; ?>

The main check is if( !$klout ), which, of course, checks to see if the value $klout is set, which we attempted to do with get_transient. If it is not, we know we need to fetch a fresh copy of the data and save it (set_transient). Since we're using a private API, you'll need to replace [API key] with your personal API key (duh).

If you wanted to get fancy, you could always work in the delete_transient function, but since these things expire with time I'm content to be the lazy type and just let decay do its work.

Go forth and cache

Equipped with your new army of drifter data you're ready to speed up page loads by reducing reliance on often slow external API calls. And if you're dealing with a rate-limited API, caching is a necessity, so you might as well do it with a supported WordPress API.

Using PHP to find a discount on a price in WordPress

by clark. 0 Comments

In today’s version of programming 101, we’re going to learn how to find the discount on a deal price. It’s pretty standard fare, but as someone who isn’t the sharpest mathematician, I figured this might be worth sharing, if for no other reason that I’ll probably need to look it up at some point in the future.

For bonus points, my example will be pulling the prices from a custom field on a WordPress post using get_post_meta. If you’re not running WordPress, you could just include the plain text prices in the script (where I set $deal_price and $old_price).

<?php
$deal_price = get_post_meta($post->ID, 'deal_price', true);
$old_price = get_post_meta($post->ID, 'old_price', true);
$discount = round(((1-($deal_price / $old_price))*100),0);
echo $discount.'%'; ?>

If you recall math class, to find a percentage you first divide the new price by the old price. Then to find the discount, you subtract from one and multiply by 100, leaving you with the actual percentage discount on the original price (rounding to zero decimal places).

Again, this is a simple one, I just wanted to log it for posterity’s sake.

What type of WordPress theme should I make?

by clark. 5 Comments

In the next few weeks, I’m going to make a series of three WordPress themes for public consumption, and I need some quick advice on which type of theme you’d like to see me release. I’m fairly certain theme one will be a news theme, and theme two will be a portfolio theme, but theme three is still in the air.

The themes will be fully responsive for perfect performance on all devices and will have only a minimal set of theme options (which will be completely removable, if desired, like I would). A good bit of the design is going to be done by @angiedoes, so I know things will come out looking sharp.

Which of the following WordPress themes should I release?

View Results

Loading ... Loading ...

Sound off in the comments below if you’ve got some extra ideas. I’m starting the builds pretty soon and I’m still open to feature suggestions…

Notes from WordUp session: Cultivating Community

by clark. 0 Comments

The following are some key links from my talk on Cultivating Community at WordUp Austin on January 21, 2012. You can find the slides over on Google Docs, but the real magic came in person that one fateful morning…

Ask questions

Topic Tueday – A new question once a week that is locked to comments from users only. A point multiplier is also in effect.

Poll Your Audience

PollDaddy – A powerful and easy to use poll plugin maintained by Automattic.
WP-Polls – A lightweight poll plugin written by Lester ‘Gamerz’ Chan.

Identity / Influence

And Me Account – A sample account from my site, showing real name, user pic, user score, percentile rank, and links to various social accounts.
Gravatar – A widely used avatar service maintained by Automattic.
Cubepoints – A lightweight point tracking system with modules that make for easy customization.
Bunchball – Full-bore gamification with badges and achievements and all that stuff.

Contests

Pick Giveaway Winner – A super simple plugin for running bespoke contests with user comments.
25 Days of Tegra – My biggest promo to date, where we gave away a device per day only to users, generating tens of thousands of user interactions.
#HackTheNews – A sample contest I ran on Android and Me where users could tweet stories with tweaked headlines, generating over 1k tweets in barely a week.
Midweek Madness – A weekly contest with usually small prizes.

Do Things with your Users

wp_user_query – A new (since 3.1) query class for working with users. Makes things super simple (compared to the old ways, at least).
update_user_meta – A super-handy function for adding and updating extra information to any user account. Use with get_user_meta.

How to create a vanity URL in WordPress with a simple page redirect

by clark. 3 Comments

Hey guys, I’ve got a super simple WordPress tip for you today that has come in handy numerous times over the years. In this age of short URLs, there are often times when you’ll need a top-level, “pretty” URL on your main domain that points to a longer, more complex URL.

For example, we are about to start an affiliate campaign with WPEngine, and my affiliate linked looked like this: http://wpengine.com?a_aid=4e6fc813411ff, which isn’t very pretty. I’d much rather link to a nice looking URL such as http://androidandme.com/wpe, which will read better in banners, in videos, and when being said aloud.

To get this done, we’re just going to make a simple custom page template that uses a simple PHP command to tell the browser that the page has moved. Take the following code and save it inside your main template folder as page-redirect.php:

<?php
/*
Template Name: Redirect
*/

$redirect_url = get_post_meta($post->ID, 'redirect_url', true);
if ($redirect_url) {
Header( 'HTTP/1.1 301 Moved Permanently' );
Header( 'Location: '.$redirect_url.'' );
}
?>

If you’ve made a custom page template before, that top part probably looks familiar to you. It’s the special bit of markup that lets WordPress know that you’ve defined a new page template, which will make our new template selectable from the ‘Edit Page’ screen in /wp-admin.

After that, we call up a custom field, “redirect_url”, which contains the long and ugly URL we want to point the browser to. Following the retrieval of that value, we use a PHP header function to send the user along to the new page.

Using your new custom template

To actually use this new custom template, there are just a few quick steps. When creating a new page, make sure that you select your custom template. There will be a drop-down in the right column where you can select your “Redirect” template (see image).

Also make sure that your set your page slug to something pretty. If you’re page is titled “Hey check out my new link”, your url slug will be hey-check-out-my-new-link. Don’t do that. Make the slug something simple, like “wpe”.

All that’s left now is to enter your long, ugly URL into a custom field labeled with the key of “redirect_url”. If you’ve never done it before, fear not, because it’s a much simpler process than people make it out to be. All you need to do is locate the “Custom Fields” box on the “Edit Page” screen and enter a key and value pair. The key is the title, “redirect_url”, and the value is the new URL, in this case: http://wpengine.com?a_aid=4e6fc813411ff

The great thing about this technique is it will work with any URL and doesn’t require a plugin. We use the technique lots of times internally, linking to our own specific posts with long URLs. As I mentioned above, it’s a great technique for video or a podcast, where you’ve actually got to say aloud Don’t forget to check out androidandme.com/wpe for a great deal on WordPress hosting.

Getting custom with Google Currents

by clark. 3 Comments

Yesterday Google announced Currents, a ridiculously awesome feed-reader-magazine-type thing that I think is shaping up to be pretty damn disruptive. In an attempt to really throw some egg in the faces of their competition, they’ve also rolled out the Google Currents Producer, giving content owners point-and-click, app-creating powers.

Google Currents is available for Android and iOS, both phones and tablets, meaning pretty much every big blog on the planet is going to be rolling onto Currents in the next few weeks. If you’d like to stand out, you’re gonna have to get your hands dirty.

The good news is that Google Currents is pretty well documented, especially for a product right out of the gate, and it uses a bunch of technology you’re probably already familiar with (Well, if you’re a web dev, that is). Every single view (table of contents, lists, articles, etc) are templated for complete control, allowing changes with simple CSS, HTML, and HTML-like markup. I say HTML-like because I thought these XML namespaces like <g:field> looked familiar enough that if you know HTML you should be comfortable inside Currents.

Some Current Lingo

Before we get started, I’m going to ramble off some lingo that I’ve picked up in the last day. Since the app is called Currents, I’ve seen lots taking to calling a single instance a Current. The actual term appears to be Edition, but I’ll probably be using them both interchangeably. Like I mentioned above, the tool to created a custom edition is called the Google Currents Producer, and can be found at http://google.com/producer.

I should also mention that this guide is aimed squarely at folks that have already logged into Producer and poked around some. Nothing that follows is crazy complex, but it might look weird if you’ve not even seen the Producer flow. Get in there and play around some!

Once you’ve created an edition, you’ll be able to add sections from some predefined choices, like Feed (RSS or Atom), Articles (Google Docs or HTML), Photos (feeds from services like Flickr), Videos (from YouTube), or Social Updates (Google+ built-in or RSS for things like Twitter). Setting up your sections is mostly a point-and-click process, so I won’t really be covering it in much detail here.

You can create and organize as many Sections as you want, along with a special Table of Contents section, which shows the most recent updates from all the other sections. Like I said earlier, nearly every single view here is templated. Each section can have individual templates (tabloid, list, photos, etc), along with templates for things like the section header and the article template. One thing I’ve noticed almost all Currents doing is defining a custom header template, so let’s start there.

Creating a Custom Header Template in Google Currents

Once you’ve got a section created (be it a feed, videos, or table of contents), you’ll probably want to slap a custom header on that bad boy. Setting it up is actually pretty easy but I found a couple “gotchas” I wanted to detail here (mainly so that other Editions I’ve subscribed to will use them, haha).

When you first create a section, the header template will be set to “Default”. Using the drop down, change that to “Custom” and have a look around. Most of the markup, should look pretty familiar, and the piece you’re looking for specifically should be near the bottom, with the class CustomHeader

[html]
<div class=’customHeader’>
<div class=’editionName’>
<g:text textid=’editionName’></g:text>
</div>
<div class=’divider’></div>
<div class=’sectionName’>
<g:text textid=’sectionName’></g:text>
</div>
</div>
[/html]

That’ll give us our first glance at some of the Currents Producer template tags, which commonly start with <g: and end with some logical suffix. You can find a full list here, along with an abbreviated version right inside the Producer by clicking “Insert Tags”.

The above markup will output my Edition’s name and the specific section name, split by a divider (you’ll find the divider CSS at the top of the template file). I’m not sure if you guys need to even see this step, but for the sake of illustration, the above code would render the following:

[html]
<div class=’customHeader’>
<div class=’editionName’>
Android and Me
</div>
<div class=’divider’></div>
<div class=’sectionName’>
Latest News
</div>
</div>
[/html]

While styling the header is just a matter of applying some simple CSS to .customHeader, there are a few other things we can do here. First, if you’ve seen our mobile site, you know we don’t even display our title text, just a logo. So that first <g:text> will be getting the boot.

Also, something you might not notice until you use the Edition inside the app itself, there is no link to the index on the main title, something that drives me crazy. Virtually all websites use that convention, most apps do, too, so I wanted it in my Current. Since I now just have a main logo and section title, I no longer need the divider, so it gets the boot as well. My new section header looked like this:

[html]
<div class=’customHeader’>
<g:link toc="true" class="logo"></g:link>
<div class=’title’>
<g:text textid=’sectionName’></g:text>
</div>
</div>
[/html]

I’m using <g:link> to link back to the table of contents. If you’d like to see what else you can link to, check out the documentation on g:link or try the “Insert Tags” popup directly within Producer. I classed the link with “logo” so that I’d be able to target it with CSS, and the rest was simple styling:

[css]
<style>
.customHeader { display:block; height:50px; position:relative; background:#000;}
.customHeader .title{color:#ccc; position:absolute; top:13px; right:20px;}
.customHeader .logo{position:absolute; top:0; left:0; width:58px; height:60px; background:url(attachment/CAAqBggKMPSRFDCRyQI-logo-corner.png) no-repeat; background-size:100% 100%;}
</style>
[/css]

If you notice that weird-looking path in there (attachment/CAAqBggKMPSRFDCRyQI-logo-corner.png), you might be sort of scared, but Producer makes uploading assets pretty dang simple. There is a media manager and every image uploaded is displayed with a path you can use in your custom markup. Simply upload your logo and grab its path from the “Insert Tags” popup available directly inside Producer.

The result is a custom header, with a logo that links to your TOC section, along with a dynamic title for the section you’re viewing. We named ours Current Edition, which you can see in the preview to the left. If you were in the Devices section, it would read Devices, thanks to our <g:text> template tag. All you’ve gotta do is make a copy of your markup to any sections you want to share this new, custom header.

There are still a few catches, like the fact that your custom header template CANNOT BE TALLER THAN 50PX. I write that in all caps because I wasted about half an hour last night trying to make it so. Anything more will definitely be cropped, no matter how many overflow:show !important‘s you add. It’s a rule I finally found on this official Google helpdoc cleverly titled Add a custom header. If my description was too breezy or if you need more help, I’d recommend consulting that doc. I’d also recommend setting up a custom header as a nice first exercise. Adding a logo to the Google Currents header is a great way to dip your toe into the pool before experimenting with more complex template tags. Speaking of which…

Earlier I was saying that if you were comfy with HTML that you’d be fine inside of Currents. What I really meant was if you know HTML and are at least a tiny bit comfortable with PHP or WordPress then you’ll be fine. Creating a list of related posts is going to make use of a loop, something that should be familiar to any blog developer.

To loop through the related posts, we’re going to make use of the g:related template tag, another find from the official Google helpdocs. Seriously, bookmark that thing. Anyway, after switching it to “Custom”, we’re going to drop the following into the bottom of our Article Template:

[html]
<h2>Related posts</h2>
<g:related max="3">
<p><g:relatedLink>
<g:relatedField fieldId="title"/>
</g:relatedLink>
<span><g:relatedField fieldId=’created’/></span>
</p></g:related>
[/html]

In the above example, the tag <g:related> will find the 3 most recent related posts and display them, along with a timestamp, at the end of the article template.

One thing to note, is that when inside a related loop, all the template tags change and get an extra “related” prefix. For example, <g:field> becomes <g:relatedField> and so on. Without the prefix, the values returned will reflect the original individual article being displayed, not that of the returned related post. It’s a small difference but a very important one. Make a mental note. Now.

While I didn’t exactly take the time to style these yet, at this point, it would just be a simple job of applying some CSS. I’m mainly just jazzed to have it working, as learning the Producer loop methodology is the first step in making my own custom TOC, tabloid, and list templates. For now, I’m not exactly sure what the match criteria is (topic, author, date, etc) but the articles seem to be relevant so I’m rolling with it.

Creating a link to an external site in Google Currents

One thing I noticed almost immediately and didn’t really like was that a lot of articles don’t display a link back to the main site anywhere. On top of that, Currents doesn’t have a way for users to add or even view comments from inside the app. Those drawbacks added up to an absolute need for a button that let users visit the original article.

Oddly enough, I see some remnant styling of a button, classed .seeOriginalLink, but I don’t see that anywhere in my templates. I’ve seen this magical button floating around in some Currents, live, but I’ve got no idea what triggers it or when it appears. What I knew for certain was that my WordPress-provided feed somehow wasn’t triggering them and I wanted them. So I did some digging and found a JS function that will launch an external link in Google Currents:

[html]
<a class="available-width-100" onclick="google.studio.openOriginalUrl();">View on Androidandme.com</a>
[/html]

Two things of note here: I used a JS onclick to fire the function and I utilized the Producer-provided class .available-width-100. The JS will open the original URL in an internal browser, along with a button to launch the site in the user’s default browser. I’d much rather launch straight to the default browser (so if anyone has figured that out, please let me know) but for now, I’ll take it.

Using .available-width-100 means that my button will fill all of the available space, be it full-screen or column. You can change that integer to any number really, I just wanted a full-width button. There are other special classes, like .g-unbreakable, which you can find documented over in the official Google support page.

The result was a nice, green button that will draw users back to androidandme.com. We have an insanely healthy user community and I wanted to make sure that people were still able to leave comments and upvotes with just a few clicks. If you’re syndicating a feed into Google Currents, I really think you should always have a link back to the original content, even if Currents sometimes doesn’t seem to want to provide one.

Import WordPress to Google Currents

I said I wasn’t really going to talk about this one in depth, and I won’t, so we’ve saved the easiest part for last. As you look around at other Currents, you’ll probably notice that people create a bunch of different sections from one blog. For example, in our Android and Me Current Edition, we’ve got a section for Latest News, Devices, Apps, etc. We even have special channels like posts from only Taylor or just giveaways from The 25 Days of Tegra. Going from WordPress to Google Currents is easier than you’d think.

The process is really simple, actually, and just requires tracking down all the custom feeds that WordPress already provides for you. Like most of us know, WordPress generates RSS and Atom feeds from recent posts, comments, and more. Every category, every tag, every author has their own feed. You can find them just by tacking /feed onto most URLs. For example, http://androidandme.com/tag/google would be http://androidandme.com/tag/google/feed. Pretty simple, huh? With that special feed URL, you could easily set up a section on only Google news in your Current.

If you’ve got a special author you’d like to feature, you could easily use his feed as a custom channel. If you’ve got a WordPress tag that’s seeing a lot of action, make a Currents section out of that specific feed. Currents even has its own CMS-style article capability, allowing you to mingle custom, non-WP data in along with your posts, but that’s probably best saved for another day.

So that’s it. Go make some Currents

Like I said at the start, I think Google Currents is one of the most gnarly and disruptive things to come down the pipe in quite some time. It allows virtually any content owner to create ridiculously custom Editions in just a matter of minutes. With some practice, I have a feeling we’re about to see even crazier things out of folks with too much time on their hands. And on those lines, I have a feeling there is about to be a really vibrant market around custom Currents themes.

For now though, I’m just happy to tinker and share.

Create one of those trendy launch pages in WordPress with no plugins

by clark. 1 Comment and 1 Reactions

I’m sure you’ve seen them around: those big, inviting launch pages that sites use to gather leads before a public launch. If you haven’t, check out Fab.com for a nice example, or take a peek at Launch Effect, one of the more popular WordPress solutions available.

In the next few weeks, we’re planning to launch AndroidHire. We’ve already got the site online, with a heavily customized theme, and handful of users actively managing job listings. The problem: we wanted to lock everything down to any non-members (while still leaving the main site intact for existing users). Looking around, I saw a handful of plugins (like Maintenance Mode) or full-on themes (like Launch Effect), but I wanted something lighter. Just a simple way to pick off logged out traffic and redirect them to a nice signup page.

The solution proved to be even easier than I imagined, so much so that I figured a blog post was in order. To sort out the guests, simply drop something like this into the very top of your theme’s header.php:

[php]
<?php if ( ! is_user_logged_in() AND ! is_page(‘Launch’)) {
header("Location: http://androidhire.com/launch");
exit(); } ?>
[/php]

The first line is a conditional with two statements. First, it checks if the user logged in. If they are not, they are redirected to my “Launch” page. Second, it checks if you’re already on the “Launch” page, simply to avoid a redirect loop.

Of course, if your data is highly sensitive, you might want to take some further steps, like disabling RSS feeds or locking down (or moving) the /wp-admin folder. This is just a quick and easy way to create a new landing page without affecting the rest of your active site.

The launch page I made is just a simple signup form that ties to Mailchimp. I’ve got two options, one for job seekers and one for job posters. Upon launch, I’ll email out to both lists and hopefully pull some extra attention from an eager crowd.