A note regarding importing serialized data in WordPress

The WordPress Importer hasn’t received much love lately.

It does work without any particular issue, it’s a tad slow, but in the end it doesn’t give you any particular headache, if not throwing a couple of warnings here and there if you have the WP_DEBUG constant turned on.

Luckily for us, a redux version is in the works, maintained by the fine folks at Human Made, that looks very promising.

The other day I was trying to import a couple of pages that had serialized data in one of their post metas and the Importer kept failing at adding those metas, while still being able to correctly create the pages.

This situation left me baffled for a while, so I started digging.

The reason for the Importer not being able to import serialized data was related to line endings contained in the array I was dealing with: in particular \r\n line endings had to be converted to \n in order for the importer not to fail.

I’ve written a recursive function you might want to pass your data through before actually saving your post meta, in case it might contain values with line endings, such as the ones generated by user input in a textarea:

function replace_endlines_deep( $data ) {
	if ( ! is_array( $data ) ) {
		return $data;
	}

	foreach ( $data as $k => $v ) {
		if ( is_array( $v ) ) {
			$data[$k] = replace_endlines_deep( $v );
		}
		else {
			$data[$k] = str_replace( "\r\n", "\n", $data[$k] );
		}
	}

	return $data;
}

So actually saving the data to the database would become:

// ... make sure to sanitize user input ...

$data = replace_endlines_deep( $data );

update_post_meta( $post_id, 'my_serialized_data', $data );

NBA Playoffs 2016 first round preview

The NBA Playoffs start in a couple of hours and sports-wise this is by far my favorite period of the year.

We can all pretty much agree on the fact that this has been an incredible and memorable regular season, for various reasons:

  • Golden State, of course, winning 73 games and breaking a record that most of us thought couldn’t be broken,
  • Steph joining the 50+40+90 club, hitting more than 400 threes, all while playing less than 35 minutes per game,
  • Kobe retiring in flames,
  • Karl-Anthony Towns having one of the best rookie seasons in recent years.

Back to the Playoffs bracket, I’d like to try and write down a couple of considerations on each pairing.

East

1. Cavs vs 8. Pistons

The Pistons finally being back in the Playoffs after a few years represent a great business card for their boss Stan Van Gundy, who was able to turn the franchise around in just a couple of seasons. Unfortunately for them, they go up against a Cavs team that is rejuvenated in spirit with Lue and LeBron co-coaching, and that should be healthier than last year. Strangely, Detroit is up 3-1 in the regular season series against the Cavs, so it’ll be an interesting series after all, but Playoffs basketball is a radically different kind of game. Cavs in 5.

4. Hawks vs 5. Celtics

The Celtics are tough. They don’t have the best roster out there, but they’re solid and well coached. Atlanta, on the other hand, is a team that will need to restructure itself and make choices comes summer time. Despite the record, I think that the Celtics might have more motivations to go through, they can affirm themselves as a solid basketball team, and they can keep the energy going, but it won’t be easy. Celtics in 6.

2. Raptors vs 7. Pacers

The Raptors have the first serious chance of getting past their first best-of-7 series in their history, and I’m not sure the Pacers, even though they’re a pretty good defensive team, are the team that can stop that. Raptors are deep, even with DeMarre Carroll nowhere near 100% health, and in the Playoffs the difference this makes is much greater. Raptors in 5.

3. Heat vs 6. Hornets

The Charlotte Hornets are one of the surprises of this seasons. They’re unsuspectedly deep, even more after moving Al Jefferson to dominate their second unit. The Heat, on the other hand, won’t have Bosh due to his health issues (get well soon, Chris!), but Johnson is playing great since joining Miami. Of all the first round, this is probably the most balanced series. I’m inclined to say Hornets in 7, but I wouldn’t be shocked if the Heat won it.

West

1. Warriors vs 8. Rockets

As I’m having a hard time finding words to describe the Warriors seasons, so am I trying to find adjectives to qualify the Rockets’. Harden is great and all, but I don’t think that the Rockets stand a chance here. Golden State is the deepest team the game has seen in the past decades, can go small or big at will (they have a fully qualified 4-men rotation in the PF/C positions, not including Green and Iguodala), which is a plus against Houston. Warriors in 4.

4. Clippers vs 5. Trail Blazers

A big big BIG round of applause for the Blazers and their leader Damien Lillard. I don’t think anyone could’ve predicted they would have been here at this point. The Clippers are, well, still the Clippers. They don’t have what it takes to go much past the first round, yet they will, and finish their season with the same sense of incompleteness that always accompanies the franchise. Clippers in 6.

2. Spurs vs 7. Grizzlies

We’re all in awe with the Warriors and what they did, but the Spurs have produced an equally impressive season, with locked down D, the usual long bench, enriched by quality veterans. Duncan is probably at his last dance, and so is Manu, which makes this Playoffs even more worth watching. The Grizzlies, on the other hand, have been clearly jinxed by and old woodoo queen of a remote Caribbean island: nearly everyone has suffered an injury, they’ve used a grand total of 28 players throughout the whole season, and they’ve gotten to these Playoffs decimated, yet showing sparks of the kind of good basketball they’re capable of. Huge props to mr. Joerger for that. Spurs in 4.

3. Thunder vs 6. Mavericks

This won’t be the Thunder’s year. Again. It’s curious that a team that has two of the top 8 players in the game, and that now has a proper coach running the show, won’t be able to accomplish what they’re meant to, that is winning the title. Yet, I can’t wait to see their matchup against the Spurs in the second round. The Mavs will probably be able to win one (Carlisle is a genius after all), but that’s about it. Thunder in 5.

I can’t wait for this to get started and see of many predictions will I miss!

On sharing knowledge

A few days ago I was thinking about how I started doing what I do for a living. I think everyone has a memory of a moment that started it all.

For me it was when I first inspected a web page to discover what was hidden behind the words “page source“. I have flashes of that memory: I remember that the page I was looking at was grey, with Times New Roman text, and the classic default blue links.

I distinctly remember though the sense of wonder that I had after opening said page in the default text editor of my operative system, changing a couple of characters, saving and hitting refresh in my browser.

It was the year 1999, or something like it, and I was officially in love.

I also distinctly remember the first time I uploaded a simple HTML document to a free hosting space I had back then.

It was a time when you had to wait a few minutes before actually be connected to the Internet, and those minutes were filled with this weird sound.

The passion that I have for what I do today started because I was able, with a little initiative on my part, to try to alter something that had been written by someone else, just for the sake of seeing what would happen.

My initiative isn’t the end of the story, but merely its beginning.

I was able to change those characters in that grey looking hypertext document because HTML is an open system, and its source can be seen and analyzed by anyone.

This is exactly why WordPress renews for me that sense of wonder almost on a daily basis, and a praise should go to WordPress itself, having created a friendly community that carries on the liberties proclaimed by the GPL.

Problems and solutions aren’t solely yours, or the plugin author’s, but they’re everybody’s territory, and everyone has the possibility to add their own little brick to the wall, actively contributing to something greater.

The other day, I was thinking that we shouldn’t take this for granted. Sadly, many companies out there still defy the logic depicted above.

Some say that Open Source is a true cultural shift, even the cultural shift of our time. What I say from my late-to-the-party perspective, is that ultimately you get what you give.

I’m starting to realize now that there’s much more to get if you share your knowledge with others.

Customizing the “Enter title here” placeholder text

Today I’ve put a new item in my ideal category of “WordPress things I didn’t even know existed”, which is the ability to edit the “Enter title here” placeholder text when creating a new post or a new item in a Custom Post Type.

While there is no way of customizing such text at the moment of the creation of the Custom Post Type, there’s a neat filter that you can use to alter it, depending on the type of the post you’re creating.

It could go something like this:

add_filter( 'enter_title_here', function( $title, $post ) {
	if ( $post->post_type === 'your-post-type' ) {
		$title = __( 'Enter Company Name' );
	}

	return $title;
}, 10, 2 );

Pretty easy, right? This is also a cool way of avoiding calling “Title” what in fact could be a “Company Name” or a “Testimonial Name”.

About WordCamp Torino 2016

Some say that a WordCamp isn’t really over until you blog about it.

So here I am, writing down a few thoughts about what has been an incredible event, WordCamp Torino 2016, the first official WordPress gathering in Italy in years.

First off, a big thank you to everyone involved in the organization of the event and the volunteers: you did an amazing job and everything went so great mainly because of your passion and commitment.

I’d also like to thank the speakers, who all delivered great presentations and I’m sure inspired not only me, but also the rest of the attendees.

Last but not least the sponsors, that made all of this possible.

For those of you who are unaware of the fact, the Italian WordPress community has been kind of lost and shattered for a good while. Even if the project was still maintained greatly and supported over the years by a very active and committed group of people, a complete sense of community was sort of missing.

Still, thanks to the wise choice of having a continent-wide WordCamp, many of us Italian WordPress enthusiasts managed to first met in Leiden, at WordCamp Europe 2014, then again in Sofia a year later, then again in Seville last June.

You know, the thing that strikes me the most about WordCamps is that by attending you not only receive invaluable new notions and tons of fresh inspiration and motivation, but you also get the opportunity of actively connecting with people all around the world.

That’s exactly what happened to us: over time, we didn’t only meet and discuss and contribute to the project, but we also became great friends, true friends and at the end of the day that’s one of the biggest reasons why everyone walked off with a big smile.

Give a group of friends the appropriate amount of time and an event like WordCamp Torino can happen and I’m sure that in the end it will be regarded of the first of many more.

I think two tweets sum it up way better that I’m equipped to do:

and lastly:

Oh yeah, I do too!

How to split a Gruntfile into multiple files

Task runners such as Grunt or Gulp can immensely speed up development, while also increasing the reliability of the code you’re writing.

The problem is that their configuration files tend to grow easily, even for small projects, and they can become hard to maintain pretty quickly.

The ones we’ve used back at my company so far follow the same path, so we though about finding a way to split them. Turns out, there is a way of doing so, and a quick search on Google returned more than one method to do it.

I’ve created a public Gist that summarizes what I’ve found.

Going in a little more detail about it, most notably here’s what I have discovered:

  • The load-grunt-tasks module allows you to automatically load the tasks you need, without having to call grunt.loadNpmTasks for each one of them; just add the tasks to the package.json file, and you’re good.
  • The loadConfig function (got the idea from Thomas Boyt) takes care of reading each configuration files that are put in a specific folder, such as tasks/options. Each file must be named as the task its declaring the configuration for (so uglify.js, for example). After reading each file, the only thing left to do is extending the main configuration object:
    grunt.util._.extend( config, loadConfig( "./tasks/options/" ) );
  • Grunt can already do the same for tasks definitions with the grunt.loadTasks( "tasks" ); instruction, which opens the tasks folder and looks for files containing tasks definitions.

So, in conclusion, just like I’m not looking back after having discovered what task runners can do for our projects, I doubt I’ll ever follow the single Gruntfile.js approach again.

WordCamp Torino 2016

For those of you that don’t know, Italy hasn’t had an official WordCamp for a few years in a row, with the last one being held in Bologna in early 2013.

In the past couple of years, the italian WordPress community has reorganized itself, with new local meetups being formed, led by reinvigorated polyglots and support teams, which now provide translations for themes, plugins, as well as WordPress core and apps, and help others over at the italian WordPress hub.

logo

This breath of fresh air led to reorganizing events as well: on April 2nd Turin will host an official WordCamp, preceded with a Contributor Day the day before.

The importance of events like this cannot be overstated, and we hope this is going to be only the first in a long list of WordPress enthusiasts gatherings in our country.

At Evolve, we have decided to help the cause micro-sponsoring the event: it’s a small contribution, of course, but with lots of these great things can be accomplished.

And, hey, there are still tickets available: if you’re around, grab one, and come say hi!

I love finding hidden functions

My primary occupation is developing on WordPress and it’s pretty much a full time activity, so if you’re like me, getting your hands dirty in code, I’m sure this has happened to you at least once: finding a function you didn’t know about, that instantly simplifies an otherwise tedious or repetitive task.

It happened to me about two years ago, when I discovered the marvels of wp_list_pluck. If you’re wondering what it does: it grabs a particular property from a multi-dimensional array or an array of objects, and stacks the result of this computation in an array of its own. Pretty neat, definitely a nice time saver.

It has happened to me just today while I was taking care of some escaping in a theme we’re building. Escaping is quite possibly the single most important thing you can do in a theme beside design, certainly more than making it chock-full of features that will likely end up unused.

If you’re new to the subject and you’re not sold yet on the concept, I suggest you take a look at this video from Computerphile, and while you’re at it spend some more time on their channel, since it’s worth every second of it.

Anyway, the function I’ve discovered today is called wp_kses_post, and it automatically filters a string of text allowing only the HTML tags that are permitted in a post’s content.

Before that, when a simple esc_html wouldn’t do it, I used to spend a good minute writing the following (or a variation of it):

wp_kses( $string, array(
	'a' => array(
		'href' => array(),
		'title' => array()
	),
	'br' => array(),
	'em' => array(),
	'strong' => array(),
)

which, long story short, is a more precise way of not allowing evil script tags where they shouldn’t be.

WordPress core has more to offer than you might know, so don’t be afraid to check it out and experiment with it, and also remember to always escape your output.

It’s ok not to know

To be honest I’ve never been much of a blogger, but over time an idea grew in my mind, unconsciously, that I didn’t have much to say either, that I didn’t have in me good enough ideas to contribute to the discussion, whatever topic the discussion might be about.

Which is plain wrong, as many would tell you. I know that now, yet I feel like struggling at the idea of publishing something that’s going to be read by strangers.

Yet, here I am, willing to make a step forward, and attempt to push something out of my mind in the wild making use of the tool I develop on pretty much every day, that is WordPress.

What the WordPress community has taught me in the last couple of years or so, is that anyone can add something, that anyone’s opinion counts, and that it’s the sum of the little and just apparently insignificant in the grand scheme of things contributions that actually makes the difference.

There’s a Jacob Riis quote that pretty much sums it up, much more eloquently that I’m able to do.

Look at a stone cutter hammering away at his rock, perhaps a hundred times without as much as a crack showing in it. Yet at the hundred-and-first blow it will split in two, and I know it was not the last blow that did it, but all that had gone before.

That is the very same quote that San Antonio Spurs’ coach Gregg Popovich has made sure it would be written on the walls of their training facility.

Today, someone in the WordPress Italian Community slack has linked to a video that put this concept back in the WordPress context, with the basic idea that it’s ok not to know, yet that shouldn’t stop anyone to have their say, to experiment, and to give their own contribution, albeit small.

Here it is!