Add Custom Metabox on Custom Post Type
=>What is a Custom Meta Box?
Custom meta boxes allow users to add extra information to posts, pages, and custom post types.
=> Creating a Meta Box
We can use add_meta_box() function used to create custom meta boxes, It is only responsible for registering and displaying custom meta boxes.
add_action( 'add_meta_boxes', 'tch_book_meta_box' ); function tch_book_meta_box() { add_meta_box( 'custom-portfolio-matabox', 'Portfolio Type', 'tch_book_meta_box_callback', //callback function 'book', //post type name 'normal' ); add_meta_box( 'custom-portfolio-matabox1', 'Star Rating ', 'tch_book_meta_box_callback1', 'book', //post type name 'normal' ); } //add metabox field function tch_book_meta_box_callback( $post ) { wp_nonce_field( 'global_notice_nonce', 'global_notice_nonce' ); $value = get_post_meta( $post->ID, '_global_notice', true ); echo '<label>Portfilio Type</label> <input type="text" id="portfolio-type" name="portfolio-type" value="">'; } function tch_book_meta_box_callback1( $post ) { echo '<label>Star Rating</label> <input type="text" id="book-star" name="book-star">'; }
=>Storing Meta Data
Now We need to save custom metadata when user save the post. We can use save_post hooks to save custom metadata.
//save meta value with save post hook add_action( 'save_post', function( $post_id ) { if ( isset( $_POST['book-price'] ) ) { update_post_meta( $post_id, 'book-price', $_POST['book-price'] ); } if ( isset( $_POST['book-star'] ) ) { update_post_meta( $post_id, 'book-star', $_POST['book-star'] ); } } );
=> Display Metadata in the front end
add_filter( 'the_content', function( $content ) { $meta_val = get_post_meta( get_the_ID(), 'book-price', true ); $meta_val_date = get_post_meta( get_the_ID(), 'book-star', true ); return $content . $meta_val . $meta_val_date; } );
Output: