Filtering active menu element class on WordPress

When using a navigation menu on WordPress, you’ve probably seen the various HTML classes that are added on active elements, such as current-menu-item, current-menu-parent, current-menu-ancestor

While that kind of classes are fine if you must fully reflect the navigation hierarchy on the menu element, there are some times that you just need a more simple approach, such as just knowing when a certain menu element must look like the active item —for instance, when using Bootstrap.

For these kind of situations, you can use a simple filter to add such a class; something like:

<?php

add_filter('nav_menu_css_class', function ($classes, $item, $args, $depth) {
    // filter by some condition... for instance, only on the "main" menu
    if ( $args->theme_location !== 'main' ) {
        return $classes;
    }
    // all the different "active" classes added by WordPress
    $active = [
        'current-menu-item', 
        'current-menu-parent', 
        'current-menu-ancestor', 
        'current_page_item'
    ];
    // if anything matches, add the "active" class
    if ( array_intersect( $active, $classes ) ) {
        $classes[] = 'active';
    }
    return $classes;
}, 10, 4);

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:

 

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.

The Cultural Defeat of Microsoft

Many people (by which I mean many Windows users”) don’t realize the huge difference between “the Windows way of doing things” and, basically, everyone elses’ way, i.e: the POSIX world which comprises all of the Unices, Linux, BSD and even OS X.

Hugo Landau writes:

From the perspective of POSIX, Windows is “alien technology” […] Windows and POSIX are fundamentally different in many ways, and lead to further “cultural” differences in how software is developed on these platforms. Windows and POSIX, then, are two “cultures”, the technical differences of the core technology itself being only a small part of that.

Read the entire piece at: The Cultural Defeat of Microsoft

Using Envoy to automate repetitive tasks

Envoy is a task runner originally developed for Laravel, but that you can also use on any other kind of project.

It’s a very easy way to define tasks with Blade syntax and simple terminal commands, which you can run on remote servers via SSH (including parallel execution) or locally.

Thanks to its simplicity, it’s great to quickly automate repetitive tasks. For instance, this is something I use for importing a replica of the production DB of a site:

@servers(['production' => 'foobar.com', 'local' => 'localhost'])

@macro('sync-db')
    dump-production-db
    get-production-db
    import-production-db
@endmacro

@task('dump-production-db', ['on' => 'production'])
    echo 'Creating production DB dump';
    cd ddbb
    mysqldump --no-autocommit --skip-extended-insert --single-transaction --ignore-table=foobar.wp_simple_history_contexts --ignore-table=foobar.wp_simple_history_history foobar_production | gzip > foobar.production.sql.gz
@endtask

@task('get-production-db', ['on' => 'local'])
    echo 'Copying DB dump from production server';
    cd ddbb
    rsync -P foobar:~/ddbb/foobar.production.sql.gz .
@endtask

@task('import-production-db', ['on' => 'local', 'confirm' => true])
    cd ddbb
    gzip -d -f foobar.production.sql.gz
    sed 's/www.foobar.com/www.foobar.lo/g' -i foobar.production.sql
    echo 'Importing production DB replica';
    mysql -v foobar_development < foobar.production.sql
@endtask

The most complete localization data you’ll ever need

The Unicode Common Locale Data Repository it’s “the largest and most extensive repository of locale data available”, so it’s pretty much the perfect solution when you need information such as:

  • Currency values, with ISO codes and visualization formats
  • Dates and times patterns, including timezones
  • List of “territories”, countries, continents, etc. with their corresponding languages, currencies
  • Translations of all of the above

You can get their data from their Downloads page in XML format (follow the links in the Data column) or, if you prefer JSON, you may the Releases on their GitHub repository.

The JSON data it’s also available for use with NPM or bower.

Horizontally scaling PHP applications

One of the most common worries of the enterprise IT world about WordPress and other Open Source apps it’s how you can scale it — which it’s kind of ironic when their enterprise-y web services response times are usually measured in the scale of tens of seconds…

DigitalOcean has published a high-level practical-overview on horizontally scaling PHP apps that’s a good starting point and I guess it could also apply to other kinds of apps as well.

Usar moment.js como helper en Ember/Handlebars

moment.js es una librería completísima para trabajar con fechas en Javascript, que puedes registrar como helper para Ember de modo de facilitar todas la tarea de parsear y formatear fechas desde y hacia distintos formatos.

Ember.Handlebars.registerBoundHelper('fecha', function(stringFecha, options){
  // options.hash es un objeto con las opciones
  var args = Ember.$.extend({
    inputFormat: 'M/D/YYYY',
    outputFormat:  'D MMM YYYY'
  }, options.hash );
  var fecha = moment(stringFecha, args.inputFormat);
  return fecha.format( args.outputFormat );
});
  • El método Ember.Handelbars.registerBoundHelper() te permite registrar un helper para propiedades que están ligadas al modelo, de modo que si éste cambia se vuelven a calcular.
  • La función que registra el helper recibe dos argumentos: el valor sobre el cual actúa el helper y un objeto de opciones.
  • El uso de Ember.$.extend() permite definir parámetros variables y opcionales e indicar sus valores predeterminados.

Uso:

// de forma normal, la propiedad post_published va a estar ligada al modelo
{{fecha post_published outputFormat="YYYY/MM/DD"}}

// también puedes usarlo de esta forma para que no cambie al cambiar los datos
{{unbound fecha post_published}}