Add Custom Post Type Parent-Child Relationship Like "Page" Post Type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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