How create meta (custom) fields in wordpress posts ?
<?php
/**
* Register meta boxes.
*/
function meta_register_meta_boxes() {
add_meta_box( 'meta-1', __( 'Custom Field', 'meta' ), 'meta_display_callback', 'contracts' );
}
add_action( 'add_meta_boxes', 'meta_register_meta_boxes' );
/**
* Meta box display callback.
*
* @param WP_Post $post Current post object.
*/
function meta_display_callback( $post ) {
?>
<div class="meta_box">
<style scoped>
.meta_box{
display: grid;
grid-template-columns: max-content 1fr;
grid-row-gap: 10px;
grid-column-gap: 20px;
}
.meta_field{
display: contents;
}
</style>
<p class="meta-options meta_field">
<label for="meta_author">Author</label>
<input id="meta_author"
type="text"
name="meta_author"
value="<?php echo esc_attr( get_post_meta( get_the_ID(), 'meta_author', true ) ); ?>">
</p>
<p class="meta-options meta_field">
<label for="meta_published_date">Published Date</label>
<input id="meta_published_date"
type="date"
name="meta_published_date"
value="<?php echo esc_attr( get_post_meta( get_the_ID(), 'meta_published_date', true ) ); ?>">
</p>
<p class="meta-options meta_field">
<label for="meta_price">Price</label>
<input id="meta_price"
type="number"
name="meta_price"
value="<?php echo esc_attr( get_post_meta( get_the_ID(), 'meta_price', true ) ); ?>">
</p>
</div>
<?php
}
/**
* Save meta box content.
*
* @param int $post_id Post ID
*/
function meta_save_meta_box( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( $parent_id = wp_is_post_revision( $post_id ) ) {
$post_id = $parent_id;
}
$fields = [
'meta_author',
'meta_published_date',
'meta_price',
];
foreach ( $fields as $field ) {
if ( array_key_exists( $field, $_POST ) ) {
update_post_meta( $post_id, $field, sanitize_text_field( $_POST[$field] ) );
}
}
}
add_action( 'save_post', 'meta_save_meta_box' );
Comments
Post a Comment