My Musings

WP3: Set parent post to post of different type

I was thrilled to find out what I could do with WordPress Custom Post Types, but very much underwhelmed that you weren’t able to set the parent of a post to be a post of a different type. That is, say you’ve created a custom post type “Chapter”, you couldn’t set the parent of a “Chapter” post to be a “Part” post. The parent had to be of the same type.

I’ve found a simple workaround which essentially replaces the “restriction” WP puts on the parent type. Besides the meta box on the edit post page, there are actually no restrictions on what post type the parent may be.

  add_action('admin_menu', function() { remove_meta_box('pageparentdiv', 'chapter', 'normal');});
  add_action('add_meta_boxes', function() { add_meta_box('chapter-parent', 'Part', 'chapter_attributes_meta_box', 'chapter', 'side', 'high');});
  function chapter_attributes_meta_box($post) {
    $post_type_object = get_post_type_object($post->post_type);
    if ( $post_type_object->hierarchical ) {
      $pages = wp_dropdown_pages(array('post_type' => 'part', 'selected' => $post->post_parent, 'name' => 'parent_id', 'show_option_none' => __('(no parent)'), 'sort_column'=> 'menu_order, post_title', 'echo' => 0));
      if ( ! empty($pages) ) {
        echo $pages;
      } // end empty pages check
    } // end hierarchical check.

Easy peasy!

  1. sugabelly reblogged this from janina
  2. janina posted this