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 );

Leave a Reply