Meet Beau Lebens

Hello there! Welcome to a new feature of the WordPress Developer Resources Blog — interviews! In this inaugural instalment, we’d like to formally introduce you to Mr. Beau Lebens, though he insists you can call him Beau. Beau is famous for many things, including Krav Maga, and instituting burrito Fridays at Automattic headquarters in San Francisco.

How did you get into working with WordPress and how long have you been at it?

Beau Lebens

Beau Lebens

I kept an eye on WordPress just out of casual interest more than anything else (in the beginning). The first time I really used it for something serious was to make a blog for a company I was working for at the time.

That was in 2005. (I had probably been following WordPress loosely for about a year before that.) When I left that company, I started a startup with a friend which was all based on WordPress (MU, as it was called at the time) and bbPress. It was called MyBabyOurBaby.com and was basically a shared scrapbooking site for families to save memories around a child.

While building that, I worked for about eight months, day and night on nothing but WordPress. I was trying to make it do a lot of things that it wasn’t supposed to, and trying to integrate with bbPress (which was really rough at the time), so it was a pretty huge learning curve. That exposure gave me pretty solid experience with WordPress though, and I was hooked. Once MyBabyOurBaby was built, but not really taking off, I started doing a lot of WP freelance work on the side. I ended up mostly working on performance and larger-scale sites since I had a bit of background in server management in addition to WP. That ended me up at Mashable.com for about six months, helping them get their site stable, building out some custom statistics/reporting systems and a few other plugins.

After that I ended up at Automattic and the rest is history :)

What’s the most important advice you can impart to a young person who wants to get into coding and development?

Dive right in. It’s just code, so you really can’t break anything too serious. Get a copy of an open source project in your language of choice (oh hai, WordPress.org!) and you can start pulling it apart to see how it works. Never be afraid to try something, even if you think it will probably break everything — that’s what “undo” is for. And backups. And source control. :)

What’s the most important challenge currently facing WordPress developers?

I think WordPress provides a lot of the components required to build amazing products (themes, plugins, entire web applications), including everything needed to make them secure. This is where the challenge comes in for developers — ensuring what they build is as secure as the core software is. Almost every security vulnerability or exploit that I hear about is via a plugin or theme. It’s up to WP developers to build software that lives up to the platform that it’s running on and to help ensure that we’re all running a safe, secure system. Having a good understanding of a few core concepts around security (especially within WP) can go a LONG way.

Knowing these two documents inside out and applying the ideas to your code will put you ahead of most other WordPress developers:

For more on Beau, check out his blog, Dented Reality, and follow him on Twitter.

Platform Updates: Posting Endpoints

We have made a few recent additions to our posting APIs that allow more control when creating posts.

You can now

  • Set a custom slug for the post permalink using the slug parameter.
  • Disable or enable the publicizing of posts, or only publicize to certain services (Twitter, Facebook, etc) using the publicize parameter.
  • Pass a custom message to the above publicize services using the publicize_message parameter.
  • Set the status of a post as “pending review” by passing pending to the status parameter.

When getting a post you can now

  • Find the featured image for a post using featured_image which will return a URL.

New Color Picker in WordPress 3.5

Some of you may have noticed the shiny new color picker in WordPress 3.5. This was a great example of collaboration between a commercial service and open source: we developed a color picker for WordPress.com to scratch our own itch, then offered it to WordPress.org. They then pushed us to make it so much better than it would have been otherwise. Everybody wins.

Find out more, including how to use it in your next WP project, on make/core: New Color Picker in WP 3.5.

Using the REST API with WordPress.org self-hosted sites via Jetpack

As of Jetpack 1.9, the WordPress.com REST API can now access self-hosted WordPress blogs with the Jetpack plugin installed.

Instead of just building for the WordPress.com platform, you can build awesome applications that interact with WordPress in general. Any applications built using the API for WordPress.com will automatically work with Jetpack-enabled sites running Jetpack 1.9 or higher.

Check out our documentation, create an app, and get started today!

Developer plugin v1.1: Themers are developers too!

We’ve pushed out v1.1 of the Developer plugin, which is packed full of goodies for WordPress theme developers.

You can now indicate that you’re working on a theme for a self-hosted WordPress install to get recommendations on a number of must-have plugins as suggested by the WordPress.com Theme Team.

We also cleaned up a few things, fixed some bugs, added some new plugins (User Switching by John Blackbourn and Pig Latin by Nikolay Bachiyski) and some other useful resources (like the _s starter theme).

(Note: we also pushed out v1.1.1 shortly after to fix an issue with the plugin slug for the Pig Latin plugin. Thanks bobbingwide for the fix.)

As always, if you’d like to check out the code and contribute, join us on Github; pull requests, bug reports, and plugin recommendations are more than welcome.

New P2 Plugin: P2 Hovercards

We’ve released a new plugin for the P2 theme that we’re calling P2 Hovercards. Hovercards are like extra bits of information about particular links that show up when you hover the corresponding inline link or object (for example, check out our Gravatar Hovercards).

With this plugin you can add hovercards to your self-hosted P2 sites. A good example of this is core trac tickets. If you look at the Make WordPress Core blog, you’ll notice that tagged Core Trac tickets are automatically linked up. So, something like #12345 links to http://core.trac.wordpress.org/ticket/12345.

With P2 Hovercards, we took this a step further. I can set it so that #12345 links to the right place, but then also show some additional information when you hover over the link. The following image is an example of what a hovercard could look like for that ticket:

You’ll notice that it gives all the necessary details about the ticket: description, recent comments, and related metadata like owner, status, and so on.

You can extend hovercards, of course, and use them for whatever service you want with a bit of code. Internally, we’re using the plugin to add details to links to support tickets, for example.

The plugin comes with a handy p2_hovercards_add_services() function for adding services:

if (function_exists( 'p2_hovercards_add_service' )
	p2_hovercards_add_service( $service, $pattern, $url, $ticket, $callback );

(Note: We recommend creating a child theme of P2 and adding the additional code to your functions.php file.)

Here’s a quick breakdown of the arguments:

  • $service is a string that is the name or slug of the service being added.
  • $pattern is a string that is the regex pattern for finding and linking up tags. For our Core Trac ticket example, you would use $pattern = '#(\d+)'
  • $url is a string that contains the regex replacement for the anchor tag that gets generated. Again, for the core trac ticket example, you would use $url = '<a href="http://core.trac.wordpress.org/ticket/$1">$0</a>'
  • $ticket is a string that contains the regex replacement for a ticket. Following the same example, you would use $ticket = '$1'
  • $callback is a callback function for generating the hovercard

The most basic callback looks something like this:

function core_trac_callback( $args ) {
	$id = (int) $args[ 'id' ];
	$url = esc_url( $args[ 'url' ] );
	$service = esc_attr( $args[ 'service' ] );

	// Do stuff with $id, $service, and $url

	return compact( 'title', 'subtitle', 'url', 'description', 'comments', 'meta' );
}

The first four things in the array ($title$subtitle$url, and $description) are just strings that will be displayed in the appropriate place on the card. The last two are a little more customizable depending what you want to do though.

Comments are stored in a 2-dimensional array with author, date, and comment fields. Meta is displayed as “Key: Value” in the black bar at the bottom of the hovercard.

More in-depth examples can be found in the examples.php file in the Github repository. As always, we invite you to join us on Github; pull requests and issues are always welcome.

Developer Plugin v1.0: Helping WordPress developers develop

Reblogged from WordPress.com VIP:

One of the great things about developing for WordPress is the number of tools available for developers. WordPress core ships with a bunch of useful features (e.g. WP_DEBUG) with many more built by the community (like our own Rewrite Rules Inspector and VIP Scanner) that make development and debugging a breeze. The hardest part is getting your environment set up just right: knowing what constants to set, what plugins to install, and so on.

Read more… 126 more words

Nginx, SPDY, and Automattic

Reblogged from Barry on WordPress:

Click to visit the original post

Yesterday, Valentin Bartenev, a developer at Nginx, Inc., announced SPDY support for the Nginx web server. SPDY is a next-generation networking protocol developed by Google and focused on making the web faster. More information on SPDY can be found on Wikipedia.

At Automattic, we have used Nginx since 2008. Since then, it has made its way into almost every piece of our web infrastructure.

Read more… 327 more words

Querying Posts Without query_posts

Here at WordPress.com, we have over 200 themes (and even more plugins) running inside the biggest WordPress installation around (that we know of anyway!) With all of that code churning around our over 2,000 servers worldwide, there’s one particular WordPress function that we actually try to shy away from; query_posts()

If you think you need to use it, there is most likely a better approach. query_posts() doesn’t do what most of us probably think it does.

We think that it:

  • Resets the main query loop.
  • Resets the main post global.

But it actually:

  • Creates a new WP_Query object with whatever parameters you set.
  • Replaces the existing main query loop with a new one (that is no longer the main query)

Confused yet? It’s okay if you are, thousands of others are, too.

This is what query_posts actually looks like:

/**
 * Set up The Loop with query parameters.
 *
 * This will override the current WordPress Loop and shouldn't be used more than
 * once. This must not be used within the WordPress Loop.
 *
 * @since 1.5.0
 * @uses $wp_query
 *
 * @param string $query
 * @return array List of posts
 */
function &query_posts($query) {
	unset($GLOBALS['wp_query']);
	$GLOBALS['wp_query'] = new WP_Query();
	return $GLOBALS['wp_query']->query($query);
}

Rarely, if ever, should anyone need to do this. The most commonly used scenario is a theme that has featured posts that appear visually before the main content area. Below is a screen-grab of the iTheme2 theme for reference.

The thing to keep in mind, is by the time the theme is starting to display the featured posts, WordPress has already:

  • looked at the URL…
  • parsed out what posts fit the pattern…
  • retrieved those posts from the database (or cache)…
  • Filled the $wp_query and $post globals in PHP.

Let’s think about it like this:

The “Main Loop” consists of 3 globals, 2 of which actually matter.

  • $wp_the_query (does not matter)
  • $wp_query (matters)
  • $post (matters)

The reason $wp_the_query doesn’t matter is because you’ll *never* directly touch it, nor should you try. It’s designed to be the default main query regardless of how poisoned the $wp_query and $post globals might become.

Back to Featured Posts

When you want to query the database to get those featured posts, we all know it’s time to make a new WP_Query and loop through them, like so…

$featured_args = array(
	'post__in' => get_option( 'sticky_posts' ),
	'post_status' => 'publish',
	'no_found_rows' => true
);

// The Featured Posts query.
$featured = new WP_Query( $featured_args );

// Proceed only if published posts with thumbnails exist
if ( $featured->have_posts() ) {
	while ( $featured->have_posts() ) {
		$featured->the_post();
		if ( has_post_thumbnail( $featured->post->ID ) ) {
			/// do stuff here
		}
	}

	// Reset the post data
	wp_reset_postdata()
}

Great! Two queries, no conflicts; all is right in the world. You are remembering to use wp_reset_postdata(), right? ;) If not, the reason you do it is because every new WP_Query replaces the $post global with whatever iteration of whatever loop you just ran. If you don’t reset it, you might end up with $post data from your featured posts query, in your main loop query. Yuck.

Remember query_posts()? Look at it again; it’s replacing $wp_query and not looking back to $wp_the_query to do it. Lame, right? It just takes whatever parameters you passed it and assumes it’s exactly what you want.

I’ll let you stew on that for a second; let’s keep going…

What if, after your featured-posts query is done and you’ve dumped out all your featured posts, you want to *exclude* any featured posts from your main loop?

Think about this…

It makes sense that you would want to use query_posts() and replace the main $wp_query loop, right? I mean, how else would you know what to exclude, if you didn’t run the featured posts query BEFORE the main loop query happened?

EXACTLY!

Paradox, and WordPress and WP_Query are designed to handle this extremely gracefully with an action called ‘pre_get_posts

Think of it as the way to convince WordPress that what it wants to do, maybe isn’t really what it wants to do. In our case, rather than querying for posts a THIRD time (main loop, featured posts, query_posts() to exclude) we can modify the main query ahead of time, exclude what we don’t want, and run the featured query as usual. Genius!

This is how we’re doing it now in the iTheme2 theme:

/**
 * Filter the home page posts, and remove any featured post ID's from it. Hooked
 * onto the 'pre_get_posts' action, this changes the parameters of the query
 * before it gets any posts.
 * 
 * @global array $featured_post_id
 * @param WP_Query $query
 * @return WP_Query Possibly modified WP_query
 */
function itheme2_home_posts( $query = false ) {

	// Bail if not home, not a query, not main query, or no featured posts
	if ( ! is_home() || ! is_a( $query, 'WP_Query' ) || ! $query->is_main_query() || ! itheme2_featuring_posts() )
		return;

	// Exclude featured posts from the main query
	$query->set( 'post__not_in', itheme2_featuring_posts() );

	// Note the we aren't returning anything.
	// 'pre_get_posts' is a byref action; we're modifying the query directly.
}
add_action( 'pre_get_posts', 'itheme2_home_posts' );

/**
 * Test to see if any posts meet our conditions for featuring posts.
 * Current conditions are:
 *
 * - sticky posts
 * - with featured thumbnails
 *
 * We store the results of the loop in a transient, to prevent running this
 * extra query on every page load. The results are an array of post ID's that
 * match the result above. This gives us a quick way to loop through featured
 * posts again later without needing to query additional times later.
 */
function itheme2_featuring_posts() {
	if ( false === ( $featured_post_ids = get_transient( 'featured_post_ids' ) ) ) {

		// Proceed only if sticky posts exist.
		if ( get_option( 'sticky_posts' ) ) {

			$featured_args = array(
				'post__in'      => get_option( 'sticky_posts' ),
				'post_status'   => 'publish',
				'no_found_rows' => true
			);

			// The Featured Posts query.
			$featured = new WP_Query( $featured_args );

			// Proceed only if published posts with thumbnails exist
			if ( $featured->have_posts() ) {
				while ( $featured->have_posts() ) {
					$featured->the_post();
					if ( has_post_thumbnail( $featured->post->ID ) ) {
						$featured_post_ids[] = $featured->post->ID;
					}
				}

				set_transient( 'featured_post_ids', $featured_post_ids );
			}
		}
	}

	return $featured_post_ids;
}

It reads like this:

  • Filter the main query.
  • Only proceed if we’re on the home page.
  • Only proceed if our query isn’t somehow messed up.
  • Only proceed if we want to filter the main query.
  • Only proceed if we actually have featured posts.
  • Featured posts? Let’s check for stickies.
  • Query for posts if they exist
  • (At this point, WP_Query runs again, and so does our ‘pre_get_posts’ filter. Thanks to our checks above, our query for featured posts won’t get polluted by our need to exclude things.
  • Take each post ID we get, and store them in an array.
  • Save that array as a transient so we don’t keep doing this on each page load.
  • We’re done with featured posts, and back in our main query filter again.
  • In our main query, exclude the post ID’s we just got.
  • Return the modified main query variables.
  • Let WordPress handle the rest.

With a little foresight into what we want to do, we’re able to architect ourselves a nice bit of logic to avoid creating a third, potentially costly WP_Query object.

Another, more simple example

The Depo Masthead theme wants to limit the home page to only 3 posts. We already learned earlier we *don’t* want to run query_posts() since it will create a new WP_Query object we don’t need. So, what do we do?

/**
 * Modify home query to only show 3 posts
 *
 * @param WP_Query $query
 * @return WP_Query
 */
function depo_limit_home_posts_per_page( $query = '' ) {

	// Bail if not home, not a query, not main query, or no featured posts
	if ( ! is_home() || ! is_a( $query, 'WP_Query' ) || ! $query->is_main_query() )
		return;

	// Home only gets 3 posts
	$query->set( 'posts_per_page', 3 );
}
add_action( 'pre_get_posts', 'depo_limit_home_posts_per_page' );

Stop me if you’ve heard this one. We hook onto ‘pre_get_posts’ and return a modified query! Woo woo!

Themes are the most common culprit, but they aren’t alone. More often than not, we all forget to clean up after ourselves, reset posts and queries when we’re done, etc… By avoiding query_posts() all together, we can be confident our code is behaving the way we intended, and that it’s playing nicely with the plugins and themes we’re running too.

WordPress.com for Windows Metro and the REST API

WordPress.com for Windows Metro

When we were starting work on the WordPress.com for Windows Metro app, we decided to build it entirely with the brand new WordPress.com REST API. The API gave us everything we needed to create a full-featured application that includes reading blogs, social features (post likes, reblogs), and creating new posts. Let’s take a look at a few code samples to see how we leveraged the API:

*note* All sample code is a condensed version of code from the Metro App. You can view the full source of the app at our trac site.

Creating a New Post

Once a user has authorized the app using OAuth (more info here), they can create new posts in the app. The /posts/new endpoint makes it very easy to create a new post via an XMLHttpRequest (xhr):


function publishPost() {
var title = "I Need a Good REST";
var content = "That's probably the corniest blog title ever created...";

var data = new FormData();

data.append('title', title);
data.append('content', content);
data.append('format', 'standard');

//note: blogID and users_access_token are received from the OAuth API
var url = 'https://public-api.wordpress.com/rest/v1/sites/' + blogID + '/posts/new';
 WinJS.xhr({
     type: 'POST',
     url: url,
     headers: { 'Authorization': 'Bearer ' + users_access_token },
     data: data
   }).then(function (result) {
     var resultData = JSON.parse(result.responseText);
  if (resultData.ID) {
    //post published!
  }
  else {
    //post publish failed
  }
}

Liking a Post

The Windows Metro app takes full advantage of the social features on WordPress.com, including likes, blog follows, and reblogs. Let’s take a look at using the /likes endpoint so that we can like a post through the API:


var curText = m.target.innerText,
likeButton = document.getElementById('like');
//just an example post_id
var post_id = 123;
//note: blogID and users_access_token are received from the OAuth API
if (curText == 'Like') {
   label.innerText = 'Liking...';
   url = 'https://public-api.wordpress.com/rest/v1/sites/' + blogID + '/posts/' + post_id + '/likes/new';
 } else {
   label.innerText = 'Unliking...';
   url = 'https://public-api.wordpress.com/rest/v1/sites/' + blogID + '/posts/' + post_id + '/likes/mine/delete';
 }

WinJS.xhr({
   type: 'POST',
   url: url,
   headers: { 'Authorization': 'Bearer ' + users_access_token }
 }).then(function (result) {
   //like operation successful!
 }, function (result) {
   //error
 });

You can see how we can also remove the like on the post by simply changing the endpoint on the post to /likes/mine/delete.

Conclusion

These examples are a small drop in the bucket of what you can do with the WordPress.com REST API. For a full list of the endpoints that are available, check out the documentation.

We’d love to hear how you are using the API in your applications! Drop us a note at our contact form to get in touch with the developer.wordpress.com team.