Best way to initialize a class on a WordPress plugin

When you’re developing a WordPress plugin, there are certain patterns and practices that are extremely useful to know and apply in order to get a better fit with the platform as a whole.

One of these things it’s what’s the better way to initialize a class on a plugin, which this answer on the WordPress StackExchange covers in great detail, while also explaining other interesting topics and recommendations such as using an autoloader and global access, registry and service locator patterns.

While you’re at it, you might also want to check these posts from Tom McFarlin:

 

John Maeda and the Open Web

Design superhero John Maeda is now working at Automattic as Global Head, Computational Design and Inclusion because he believes in the open web…

The fact that so many people are commenting about it on Facebook, just proves how hard his new mission is… And how easy is to just not “get” why it’s so important. 

Using Basic Authentication with the WordPress HTTP API

Basic Authentication it’s often used as a simple security measure or as a temporary authentication method while developing with certain APIs.

While the WordPress HTTP API doesn’t have explicit support for basic authentication, it’s still possible to use it as a header:

$request = wp_remote_post(
  $remote_api_endpoint,
  array(
    'body'    => array( 'foo' => 'bar' ),
    'headers' => array(
      'Authorization' => 'Basic '. base64_encode( $username .':'. $password )
    )
  )
);

Remember that if you’re sending an unencrypted request, all the headers will be sent in plain text, so you should only use it over HTTPS.

Use get_the_terms() instead of wp_get_object_terms()

I was recently debugging the front page of a WordPress site and found a lot of queries to the terms and term relationships database tables.

Digging a little deeper, I found that the culprit were a set of functions that were calling wp_get_object_terms() to get the terms from a set of looped posts… and then I thought… “wait a minute, doesn’t WordPress should be using the object cache for this?”

Well, it turns out that wp_get_object_terms() always queries the database.

If you’re looping over WP_Query results, you should prefer get_the_terms() instead. It’s pretty much the same for most use cases, but it uses the object cache, which by default gets populated with the terms for the posts matching your query — unless you specifically set update_post_term_cache as false when instantiating WP_Query.

The are several differences, though: wp_get_object_terms() can take arrays as the first and second argument, while get_the_terms() can only take the post ID (or object) as first argument (so you can’t get the terms for a bunch of posts on one function call) and a string for taxonomy (so you can’t get the terms for several taxonomies); and you can use a third argument on the former, which the latter doesn’t have.

You could still emulate some of this, and still benefit from using the object cache; for instance, let’s see how you would get the names of the my_custom_tax terms for the current post, ordered by use on a descending way.

// using wp_get_object_terms()
$popular_terms = wp_get_object_terms( $post->ID, 'my_custom_tax', array( 
    'orderby' => 'count',
    'order'   => 'DESC',
    'fields'  => 'names'
) );

// using get_the_terms()
$popular_terms = get_the_terms( $post->ID, 'my_custom_tax' );
// $popular_terms will be ordered alphabetically, so let's order by count
$popular_terms = usort( $popular_terms, function( $a, $b ){
    if ( $a->count < $b->count ) {
        return 1;
    }
    if ( $a->count > $b->count ) {
        return -1;
    }
    return 0;
} );  
// we only need slugs, so...
$popular_terms = wp_list_pluck( $popular_terms, 'name' );

Even if it’s somewhat troublesome, it’s probably worth the effort if you’re trying to maximize for performance.

Unified search with Elasticsearch and WordPress

During the last months of 2012, and as a part of AyerViernes, we worked on one of those projects that is as challenging as delightful to take part in, developing a unified search system for a network of over 200 WordPress sites (both single-install and multisite).

We developed a real-time sync plugin integrating the WordPress sites with an Elasticsearch instance with different content types (mappings) that give us plenty of room to index and search in hundreds of thousands documents generated by the university staff.

You can read the complete post (in spanish) on Medium: Desarrollo de sistema de búsqueda transversal: +200 sitios a un clic de distancia

Importar tu base de datos de WordPress (de la forma más rápida)

Uno de los grandes aprendizajes que he podido aplicar al desarrollo de sitios con WordPress, y del cual soy particularmente entusiasta de sermonear es la necesidad de mantener una versión local de desarrollo lo más parecida posible a lo que vas a utilizar en producción, lo que además se apoya y soporta un montón de otras buenas prácticas como evitar el cowboy coding, utilizar control de versiones, etc.

Puesto que para el cliente no se trata de uno de los objetivos del proyecto, la capacidad de importar una base de datos para tener una réplica de desarrollo debe ser algo sencillo y rápido de ejecutar. Aunque existen múltiples plugins y herramientas para hacerlo, para mí la forma más sencilla es recurrir a herramientas muy básicas a través de la línea de comandos.

Continue reading “Importar tu base de datos de WordPress (de la forma más rápida)”