Can I use custom post types to create a parent/child relationship?

I’m using this code for a metabox in a current project I’m working on:

function parent_select ($parent_type) {
    global $post;
    global $wpdb;
    $query = "SELECT ID, post_title FROM $wpdb->posts WHERE post_type="{$parent_type}" AND post_status="publish" ORDER BY post_title";
    $results = $wpdb->get_results($query, OBJECT);
    echo '<select name="parent_id" id="parent_id">';
    echo '<option value = "">None</option>';
    foreach ($results as $r) {
        echo '<option value="', $r->ID, '"', $r->ID == $post->post_parent ? ' selected="selected"' : '', '>', $r->post_title, '</option>';
    }
    echo '</select>';
}

This code outputs a select box that is populated by the post titles and post id’s of all posts of a certain type. If you place this in a metabox of a child post type, all you would need to do is to is select a parent post and update. WordpPress already looks for a form element called ‘parent_id’ to set a post’s parent, so there is no other code really needed, except to create the metabox:

add_meta_box('parent_series', 'Series', 'show_series_metabox', 'episode', 'side', 'high');  //add a side metabox
function show_series_metabox() {
    parent_select('series');
    echo 'Please select series';
}

Ironically enough, I’m doing this for a similar situation: I have a post type for a series, 2 other post types, one for episodes and one for DVD releases, both of which hook up to a series as a parent-child relationship using the post_parent field of a post.

Special thanks to @MikeSchinkel, whose code I modified

Leave a Comment