How to Convert Plugins to Use Custom Post Types

If you’re a plugin developer whose been using custom tables for storing information in WordPress the transition to custom post types may be daunting.

However, as WordCamp UK showed there’s no need to as it’s a really simple process, thanks to a demonstration by Kieran O’Shea.

It’s really simple, and here are the two steps;

1. Create your custom post type

Create, install and activate the following plugin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*
Plugin Name: Example Custom Post
Plugin URI: http://www.kieranoshea.com
Description: Allows the demonstration of custom posts
Author: Kieran O'Shea
Author URI: http://www.kieranoshea.com
Version: 1.0
*/

function create_post_type() {
  register_post_type( 'calendar_event',
    array(
      'labels' => array(
        'name' => __( 'Events' ),
        'singular_name' => __( 'Event' ),
        'add_new' => __('Add New'),
        'add_new_item' => __('Add New Event'),
        'edit_item' => __('Edit Event')
      ),
      'public' => true,
      'has_archive' => true,
      'rewrite' => array('slug' => 'events') 
    )
  );
}
add_action( 'init', 'create_post_type' );

function my_rewrite_flush() {
  create_post_type();
  flush_rewrite_rules();
}
register_activation_hook(__FILE__, 'my_rewrite_flush');

Note the last few lines, especially flush_rewrite_rules() which make sure your new post type can be viewed on your site.

2. Move your existing content to your new custom post type

Now all you need to do is loop through your database entries and add them as new posts for your new custom post type!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
A quick command line script to migrate a table of data to custom posts
*/

// Turn off errors as we're sort of outside wordpress 
// and the browser and that can cause warnings
define('WP_DEBUG', false);

// Require the standard WordPress header
require(dirname(__FILE__).'/wp-blog-header.php');

// Tell the user what we're about to do
echo 'Migrating table WP_CALENDAR to custom post type CALENDAR_EVENT 
';

// We need some of the WordPress globals to proceed
global $wpdb;

// Get all our events
$events = $wpdb->get_results("SELECT * FROM wp_calendar");

// How many are there?
echo sizeof($events).' events will be imported...

';

// Loop through 'em and load 'em to WordPress
if (!empty($events))
  {
    foreach ($events as $event)
      {
        $ent['post_type']    = 'calendar_event';
        $ent['post_content'] = $event->event_desc;
        $ent['post_parent']  = 0;
        $ent['post_author']  = 1;
        $ent['post_status']  = 'publish';
        $ent['post_title']   = $event->event_title;
        $entid = wp_insert_post ($ent);
        if ($entid == 0) { 
          echo 'Failed to migrate event "'.$event->event_title.'"
          '; 
        } else { 
          echo 'Migrated event "'.$event->event_title.'"
          '; }
      }
    }

// Tell the user we're all done
echo '
Done!
';

Now, you need to run that from the command line. So, grab yourself a tool like PuTTY for Windows or use the Mac Terminal and connect to your server to run the script.

Job done! You’ll see a new menu item in your dashboard with all your new custom posts.

Thankfully, Kieran has provided a mini site for WordCamp UK where you can see his full presentation and download the code above too.

I spoke to Kieran afterwards who provided a useful summary of his session:

Featured Plugin - WordPress Google Maps Plugin

Simply insert google maps into posts, sidebars and pages - show directions, streetview, provide image overlays and do it all from a simple button and comprehensive widget.
Find out more

Featured Plugin - WordPress Infinite SEO Plugin

Fully integrated with the SEOMoz API, complete with automatic links, sitemaps and SEO optimization of your WordPress setup - this is the only plugin you need to help you rank your site number 1 on Google - nothing else compares.
Find out more

Featured Plugin - WordPress Wiki Plugin

To get a wiki up and running you used to need to install Mediawiki and toil away for days configuring it... not any more! This plugin gives you *all* the functionality you want from a wiki, in WordPress!!!
Find out more

Featured Plugin - WordPress Pop-Up Chat Plugin

No javascript required, no third part chat engine, just fully featured chat right in your own database on your own WP sites - couldn't be easier.
Find out more

Featured Plugin - WordPress Q&A Site Plugin

It's now incredibly easy to start your own Q&A site using nothing more than WordPress - The Q&A plugin simply and brilliantly transforms any site, or page, into a perfect support or Q&A environment.
Find out more

Featured Plugin - WordPress Newsletter Plugin

Now there's no need to pay for a third party service to sign up, manage and send beautiful email newsletters to your subscriber base - this plugin has got the lot.
Find out more

Featured Plugin - WordPress Facebook Plugin

Would you like to add Facebook comments, registration, 'Like' buttons and autoposting to your WP site? Well, The Ultimate Facebook plugin has got that all covered!
Find out more

Featured Plugin - WordPress Appointments Plugin

Take, set and manage appointments and client bookings without having to leave WordPress. Appointments+ makes it easy.
Find out more

Featured Plugin - WordPress Membership Site Plugin

If you're thinking about starting a paid, or just private, membership site then this is truly the plugin you've been looking for. Easy to use, massively configurable and ready to go out of the box!
Find out more

Comments (7)

  1. I have created a file in a new folder as plugin. I have used the the first code in that file. But where should I use the second code ? In the same file ?

    Thanks !

  2. Hiya VNU,

    That second bunch of code needs to be in a separate file. Call it migrate-custom-posts.php for good measure.

    You’ll then need to run it on the command line. You’ll need a tool like PuTTY to do that.

    The command will be as simple as;
    $ php migrate-custom-posts.php

    Phil

Participate