THE PENDING DRAFT

Yoda Conditions

April 25, 2015

Have you ever heard of Yoda Conditions? Maybe you saw some code written like this:

if ( true == $the_force ) {
    $victorious = you_will( $be );
}

I never really got why it could be useful to write a condition in that order until i found this part of the WordPress’s PHP Coding Standards:

In the above example, if you omit an equals sign (admit it, it happens even to the most seasoned of us), you’ll get a parse error, because you can’t assign to a constant like true. If the statement were the other way around ( $the_force = true ), the assignment would be perfectly valid, returning 1, causing the if statement to evaluate to true, and you could be chasing that bug for a while.

Now that makes a whole lot of sense, so make sure to write your conditions in that order from now on, even if it sounds strange at first. Or, as it is appropriately stated in the Coding Standards:

A little bizarre, it is, to read. Get used to it, you will.

PHP Coding Standards – Yoda Conditions

Optimizing a Custom Query in WordPress

April 14, 2015

With the WP_Query class WordPress provides a powerful tool to query things from the database. But as with most powerful things, you can also mess things up quite a bit if you’re not careful enough.

With great power comes great responsibility.

(Voltair, Yoda, Uncle Ben in Spiderman or whoever said it first)

Let me give you an example of a query we needed in a project and how we implemented it.

The Goal

We want to get the IDs of all Attachments (images in this case), that are attached to any post of a particular Custom Post Type.

The Wrong Way

The good thing about WordPress is that you can find a snippet for pretty much anything with a simple Google Search. The bad thing about WordPress is that you can find a snippet for pretty much anything with a simple Google Search. Often it’s as easy as throwing a snippet into your plugin or functions.php in your theme and it just magically works.

Here’s the first “solution” i found somewhere on StackOverflow:

// Query for all posts of post_type 'post-type-name'
$cpt_query = new WP_Query(
  array(
    'post_type' => 'post-type-name',
    'posts_per_page' => -1 // get everything
  )
);

// Create an empty array for our attachment ids
$attachment_ids = array();

// Run a Loop through our CPT-Query
if( $cpt_query->have_posts() ){
  while( $cpt_query->have_posts() ){
    $cpt_query->the_post();

    // Inside the Loop, get all attachments which are children of this post
    $attachments = get_children(
      array(
        'post_parent' => get_the_ID(),
        'post_type' => 'attachment'
      )
    );

    // Add the attachment id to our array
    foreach ( $attachments as $attachment ) {
      $attachment_id = strval( $attachment->ID );
      array_push( $attachment_ids, $attachment_id );
    }
  }
  wp_reset_postdata();
}

 

While this worked perfectly as it should, it had a pretty expensive overhead. Right now we query for all posts of that Post Type, then load all information about that post, loop through every single one of them and inside that Loop we query again for all attachments, load all data and again loop through every single one of them to get the ids.

We add a lot of queries post per post while looping through them, not good! This might not be a problem when you only have some posts with a handful of attachments. But because of the way this query was built the queries would increment for every post which would easily lead to thousands of queries when more posts and attachments are added.

So, what can we do to fix this? Let’s see.

First of all, it’s important to realize that you have a problem, preferably before anyone else does. I use the Query Monitor Plugin during development to display the amount of queries (among other useful information) in the admin bar. On top of that, it’s a good idea to test your plugin/theme not only on a blank installation but also to create, delete, add, move as much as you can to check if there are issues you won’t notice otherwise.

‘fields’ => ‘ids’ to the rescue

Inside WP_Query we can define which fields we want to retrieve by adding 'fields' => '...' to the query. That way we won’t load every single piece of information about the posts we find, but only what we need: the IDs.

$cpt_query = new WP_Query(
  array(
    'post_type' => 'post-type-name',
    'posts_per_page' => -1,
    'fields' => 'ids'
  )
);

 

This will get us an array of IDs. We don’t have to loop through them anymore and can directly make a second query to get our attachments.

$attachment_query = new WP_Query(
  array(
    'post_type' => 'attachment',
    'posts_per_page' => -1,
    'post_status' => 'any', // Not sure if this is needed, but it makes sure we really get every attachment
    'post_parent__in' => $cpt_query->posts, // Look for children of the ids from our first query
    'fields' => 'ids' // Again, we only want to get the ids
  )
);

 

This second query gets all attachments that are children of (attached to) one of the posts we got in the first query. The result of $attachment_query->posts will again be an array of IDs, this time for the attachments.

This means instead of potentially thousands we will only ever have two queries, regardless of the amount of posts and attachments.

The Solution

To sum up here’s the complete code we use today in our plugin (we added some more parameters and checks, but it’s technically identical).

function pdr_get_attachments_from_cpt( $query ) {
  $cpt_query = new WP_Query(
    array(
      'post_type' => 'post-type-name',
      'posts_per_page' => -1,
      'fields' => 'ids'
    )
  );

  $attachment_query = new WP_Query(
    array(
      'post_type' => 'attachment',
      'posts_per_page' => -1,
      'post_status' => 'any', // Not sure if this is needed, but it makes sure we really get every attachment
      'post_parent__in' => $cpt_query->posts, // Get children of the ids from our first query
      'fields' => 'ids' // Again, we only want to get the ids
    )
  );
}

 

In our case we hooked that function to the pre_get_posts filter to exclude those attachments from all queries, I left that part out for the sake of simplicity. Let me know if you want to see the complete code.

This is exactly the kind of thing I meant when I wrote about taking things apart as a regular learning habit. It didn’t took a whole lot of time to figure out what was going wrong with the original function, I fixed a piece of code which would have gotten us into trouble later on and I learned a few things about how queries in WordPress work.

What did you learn today?

How Seville transformed itself into the cycling capital of southern Europe

April 12, 2015

Seville now has 75 miles of segregated lanes, with other routes radiating out from the loop around the old town. It also has a municipal bike hire scheme, like those in Paris and London, called SEVici, with 2,500 bikes and 250 docking stations.

It is additionally trying to link cycling with public transport. Passengers arriving at the city’s main bus station can use their ticket to borrow one of nearly 200 separate rental bikes, free for the whole day. The city’s university has yet another scheme, in which students are provided with bikes for the academic year.

Looking forward to WordCamp Europe in June even more when i read this.

How Seville transformed itself into the cycling capital of southern Europe

Git Structure for WordPress Projects

April 9, 2015

A great post about whats the best git structure for WordPress projects. I completely agree with Peter Suhm on this one.

I have ranted about the subject of repository structure before and I have strong opinions about it. In my opinion there is one – and only one – way to structure Git repositories in a WordPress context. That one way is the one-package / one-repository approach. Let me explain why.

Putting the complete WP core into your repo is something i see a lot, but it always feels wrong and bloated to me. One plugin/theme = one repo is the way to go.

Plus i learned about .gitattributes in his post which seems to be a good way to specify which files should get bundled in the final .zip when your project gets downloaded.

Git and WordPress: 3 Tips to Do It Better

ThemeReview.co now also accept plugins

April 7, 2015

Just a few months after their launch, Justin Tadlock and Emil Uzelac of ThemeReview.co announced that they intend to also accept plugins for review in the future. For now it’s limited to a few plugins until they figured out the pricing structure and overall process and the cost will be evaluated individually based on the complexity of each plugin. You find some more about it in this post over at the WPTavern.

ThemeReview.co – We’re now accepting plugins

Speed Optimization Myths

April 6, 2015

Optimizing your website for speed can be a complex issue, especially for non-developers. A lot of guides and articles over-simplify by providing broad advice that isn’t applicable to every website and shouldn’t be taken at face value. Here’s a few commonly-spouted tips that need some clarification.

Some good advice to think about next time you’re optimizing a page for performance.

5 Speed Optimization Myths

On the WordPress REST API

April 3, 2015

The REST API is shaping up to be an awesome reflection of WordPress itself. WordPress is a tool that provides a basic starting point for a CMS in five minutes or less, which can be expanded on pretty much infinitely.

The REST API is no different. It provides a fully functional API out of the box, ready for anyone to use, with all the power needed for site and plugin developers to easily customize.

Some insights on the development of the WP-API. I only scratched the surface a bit up until now but already look forward to all the possibilities this will bring to WordPress. If you haven’t played with the Development Plugin already, you definitely should.

On the WordPress REST API

register_meta()

March 31, 2015

The solution is easy and relies only on core functionality. It’s a simple function called register_meta(). This function is almost identical to the more commonly used register_setting(). When we use register_setting(), we are able to register a callback function. That way, when anyone saves this setting that’s being registered, it passes through that callback for sanitation and validation.

We can do the exact same thing for meta fields with register_meta and not just post meta, but any type of meta data. And, it’s easy to do.

Didn’t know about register_meta() and i think i need to rewrite some stuff now.

Staying safe and DRY with register_meta()

Using Nonces to prevent Request Forgery

March 29, 2015

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

This article on CSS-Tricks is the second in a series of articles about WordPress Frontend Security. In this one Andy Adams explains CSRF (Cross-Site Request Forgery) and what nonces are, how they are used in WordPress and why it’s so important that you use them.

CSS-Tricks on WordPress Frondend Security – CSRF and Nonces