Custom Meta Box vs Custom Fields
Custom fields allow users to add key/value pairs of data to a post, page, or custom post type. But meta boxes can have many varieties of input fields such as color picker, file upload, dropdowns, and so on. We need a Custom Post Type To add the meta boxes.
Syntax of add_meta_box
add_meta_box( string $id, string $title, callable $callback, string|array|WP_Screen $screen = null, string $context = 'advanced', string $priority = 'default', array $callback_args = null );
Add Meta Box in Post
You can also add it in custom post and page - just place of 'post' Your post type like page,event etc. Copy all code one by one and past it in functions.php file.Where you want to show-
The context within the screen where the box should display. Available contexts vary from screen to screen. Post edit screen contexts include 'normal', 'side', and 'advanced'. Comments screen contexts include 'normal' and 'side'. Menus meta boxes (accordion sections) all use the 'side' context. Global default is 'advanced'. Default: 'advanced'.add_action( 'add_meta_boxes', function() { add_meta_box( 'reading_time_id', 'Add Your Reading Time', 'custom_post_meta', 'post', 'side' ); } );
Meta callback function -
You can change input type and name and set a default value in value.//Meta callback function function custom_post_meta( $post ) { $wpdocs_meta_val = get_post_meta( $post->ID, 'reading_time', true ); ?> <input type="text" name="reading_time" value=""> <?php }
Save meta value with save post hook
'reading_time' is cutom meta_id like dive id, You can chage it.//save meta value with save post hook add_action( 'save_post', function( $post_id ) { if ( isset( $_POST['reading_time'] ) ) { update_post_meta( $post_id, 'reading_time', $_POST['reading_time'] ); } } );
Show meta value in post
show meta value in post. You can display it any where. in this example we show it by short code you can use filter.// show meta value after post content function show_read_time(){ ob_start(); $meta_val = get_post_meta( get_the_ID(), 'reading_time', true ); echo $meta_val; return ob_get_clean(); } add_shortcode("read_time","show_read_time"); //shortcode [read_time] add it on front
2 Comments
Please update html -
ReplyDelete<input type="text" name="reading_time" value="<?php echo $wpdocs_meta_val; ?>">
Use in wp Query -
ReplyDelete$query = new WP_Query(
array('post_type' => 'post',
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'reading_time',
'value' => '10',
'compare' => '<='
)
))
);