Importing Posts From Custom Sources Into WordPress

WordPressOver the past few days, I have been working on some custom scripts to import information from an older system into WordPress as a custom post type with a great deal of custom meta information. I quickly found the key to doing so is to use the wp_insert_post() function.

In my case, I am importing information from XML files into PHP arrays. I am then using an array_map() callback to pull the information out of the imported array, format it the way I want it, assign the appropriate keys to it and more. From there, I am using the wp_insert_post() function and the add_post_meta() function to push that information into the WordPress database.

Before inserting a new post, I use a function to check the database and make sure a post doesn’t already exist with that same title. Then, I insert the post. Finally, I add the custom meta information.

My function to check for existing posts looks like:

function wp_exist_post_by_title($title_str) {
	global $wpdb;
	return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM " . $wpdb->posts . " WHERE post_title = '" . $title_str . "'" ), 'ARRAY_A');
}

Then, I use a function similar to the following to actually import the posts:

function _htmlcenter_import_posts( $posts ) {
	if( !is_array( $posts ) )
		return false;

	$new_posts = array();
	foreach( $posts as $p ) {
		$post_id = wp_exist_post_by_title( $p['post_title'] );
		if( !$post_id ) {
			$post_title = $p['post_title'];
			$post_id = wp_insert_post( $p );

            /* Set a custom post taxonomy - if the taxonomy is hierarchical,
            you have to use the term ID */
			wp_set_post_terms( $post_id, $p['custom_taxonomy'], 'custom_taxonomy' );

            if( array_key_exists( $p['first_custom_meta_field'], $degrees ) ) {
				delete_post_meta( $post_id, 'first_custom_meta_field' );
				add_post_meta( $post_id, 'first_custom_meta_field', array_values( $custom_meta_fields[$p['first_custom_meta_field']] ) );
			}
			delete_post_meta( $post_id, 'second_custom_meta_field' );
            add_post_meta( $post_id, 'second_custom_meta_field' );
		} else {
			$post_title = __( 'A post with the title of ' . $post_id['post_title'] . ' already exists' );
			$post_id = $post_id['ID'];
		}
		$new_posts[$post_id] = $post_title;
	}
	return $new_posts;
}

I hope that helps anyone looking to import old information into a new WordPress blog.

One Response

  • […] employees. Should you ever choose to move your employee directory into WordPress, you can easily import the information as posts (most likely a custom post type) and then pull the employee images and add them to WordPress, […]