- Navigate to the ch4-book-reviews folder of the WordPress plugin directory of your development installation.
- Open the ch4-book-reviews.php file in a code editor.
- Add the following line of code after the existing functions to register a function to be called when the administration interface is visited:
add_action( 'admin_init', 'ch4_br_admin_init' );
- Add the following code section to provide an implementation for the ch4_br_admin_init function and register a meta box to be associated with the book_reviews post type:
function ch4_br_admin_init() {
add_meta_box( 'ch4_br_review_details_meta_box',
'Book Review Details',
'ch4_br_display_review_details_meta_box',
'book_reviews', 'normal', 'high' );
}
- Insert this function to implement the ch4_br_display_review_details_meta_box function and render the meta box contents:
function ch4_br_display_review_details_meta_box( $book_review ) {
// Retrieve current author and rating based on review ID
$book_author =
esc_html( get_post_meta( $book_review->ID,
'book_author', true ) );
$book_rating =
intval( get_post_meta( $book_review->ID,
'book_rating', true ) );
?>
<table>
<tr>
<td style="width: 100%">Book Author</td>
<td><input type="text" size="80"
name="book_review_author_name"
value="<?php echo $book_author; ?>" /></td>
</tr>
<tr>
<td style="width: 150px">Book Rating</td>
<td>
<select style="width: 100px"
name="book_review_rating">
<!-- Loop to generate items in dropdown list -->
<?php
for ( $rating = 5; $rating >= 1; $rating -- ) { ?>
<option value="<?php echo $rating; ?>"
<?php echo selected( $rating, $book_rating ); ?>>
<?php echo $rating; ?> stars
<?php } ?>
</select>
</td>
</tr>
</table>
<?php }
- Add the following code segment to register a function that will be called when posts are saved to the database:
add_action( 'save_post', 'ch4_br_add_book_review_fields', 10, 2 );
- Add an implementation for the ch4_br_add_book_review_fields function defined in the previous add_action call:
function ch4_br_add_book_review_fields( $book_review_id,
$book_review ) {
// Check post type for book reviews
if ( 'book_reviews' == $book_review->post_type ) {
// Store data in post meta table if present in post data
if ( isset( $_POST['book_review_author_name'] ) ) {
update_post_meta( $book_review_id, 'book_author',
sanitize_text_field(
$_POST['book_review_author_name'] ) );
}
if ( isset( $_POST['book_review_rating'] ) &&
!empty( $_POST['book_review_rating'] ) ) {
update_post_meta( $book_review_id, 'book_rating',
intval( $_POST['book_review_rating'] ) );
}
}
}
- Find the ch4_br_create_book_post_type function, where the new book type was originally created, and remove the custom-fields element from the supports array:
'supports' => array( 'title', 'editor', 'comments', 'thumbnail' ),
- Save and close the plugin file.
- Open the previously created Book Review to see the new Book Review Details meta box, containing a text field to specify the author and a drop-down list for the rating: