Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add Custom Post Type Parent-Child Relationship Like "Page" Post Type
/**
* Source: http://justintadlock.com/archives/2013/10/07/post-relationships-parent-to-child
* Improved by Kharis Sulistiono
* Improvements:
* - Add "Select Relation" option
* - Add else conditional when no post created.
*
* To make that code works, make sure your post type supports custom meta box by adding 'register_meta_box_cb'
*
* From the code above, the CPT has to able to call a metabox callback function 'my_add_meta_boxes':
*
* 'register_meta_box_cb' => 'my_add_meta_boxes'
*
**/
/* Hook meta box to just the 'place' post type. */
add_action( 'add_meta_boxes_place', 'my_add_meta_boxes' );
/* Creates the meta box. */
function my_add_meta_boxes( $post ) {
add_meta_box(
'my-place-parent',
__( 'Relation', 'example-textdomain' ),
'my_place_parent_meta_box',
$post->post_type,
'side',
'core'
);
}
/* Displays the meta box. */
function my_place_parent_meta_box( $post ) {
$parents = get_posts(
array(
'post_type' => 'your-post-type',
'orderby' => 'title',
'order' => 'ASC',
'numberposts' => -1
)
);
if ( !empty( $parents ) ) {
echo '<select name="parent_id" class="widefat">'; // !Important! Don't change the 'parent_id' name attribute.
echo '<option value="">Select Relation</option>';
foreach ( $parents as $parent ) {
printf( '<option value="%s"%s>%s</option>', esc_attr( $parent->ID ), selected( $parent->ID, $post->post_parent, false ), esc_html( $parent->post_title ) );
}
echo '</select>';
} else {
echo '<select name="parent_id" class="widefat">'; // !Important! Don't change the 'parent_id' name attribute.
echo '<option value="">Select Relation</option>';
echo '</select>';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.