Event Meta
class events_meta_box {
public function __construct() {
if ( is_admin() ) {
add_action( 'load-post.php', array( $this, 'init_metabox' ) );
add_action( 'load-post-new.php', array( $this, 'init_metabox' ) );
}
}
public function init_metabox() {
add_action( 'add_meta_boxes', array( $this, 'add_metabox' ) );
add_action( 'save_post', array( $this, 'save_metabox' ), 10, 2 );
}
public function add_metabox() {
add_meta_box(
'event_meta',
'Event Detail',
array( $this, 'render_metabox' ),
'events',
'advanced',
'core'
);
}
public function render_metabox( $post ) {
// Retrieve an existing value from the database.
$event_killdate = get_post_meta( $post->ID, 'event_killdate', true );
$event_time = get_post_meta( $post->ID, 'event_time', true );
$event_location = get_post_meta( $post->ID, 'event_location', true );
// Set default values.
if( empty( $event_killdate ) ) $event_killdate = '';
if( empty( $event_time ) ) $event_time = '';
if( empty( $event_location ) ) $event_location = '';
// Form fields.
echo '<table class="form-table">';
echo ' <tr>';
echo ' <th><label for="event_killdate" class="event_killdate_label">' . 'Display Until' . '</label></th>';
echo ' <td>';
echo ' <input type="date" id="event_killdate" name="event_killdate" class="event_killdate_field" placeholder="' . '' . '" value="' . esc_attr__( $event_killdate ) . '">';
echo ' <p class="description">' . 'Enter the date to display the event as upcoming until' . '</p>';
echo ' </td>';
echo ' </tr>';
echo ' <tr>';
echo ' <th><label for="event_time" class="event_time_label">' . 'Enter the Time of the Event' . '</label></th>';
echo ' <td>';
echo ' <input type="text" id="event_time" name="event_time" class="event_time_field" placeholder="' . 'Enter the time' . '" value="' . esc_attr__( $event_time ) . '">';
echo ' </td>';
echo ' </tr>';
echo ' <tr>';
echo ' <th><label for="event_location" class="event_location_label">' . 'Event Location' . '</label></th>';
echo ' <td>';
echo ' <input type="text" id="event_location" name="event_location" class="event_location_field" placeholder="' . '' . '" value="' . esc_attr__( $event_location ) . '">';
echo ' <p class="description">' . 'Where is this happening?' . '</p>';
echo ' </td>';
echo ' </tr>';
echo '</table>';
}
public function save_metabox( $post_id, $post ) {
// Sanitize user input.
$event_new_killdate = isset( $_POST[ 'event_killdate' ] ) ? sanitize_text_field( $_POST[ 'event_killdate' ] ) : '';
$event_new_time = isset( $_POST[ 'event_time' ] ) ? sanitize_text_field( $_POST[ 'event_time' ] ) : '';
$event_new_location = isset( $_POST[ 'event_location' ] ) ? sanitize_text_field( $_POST[ 'event_location' ] ) : '';
// Update the meta field in the database.
update_post_meta( $post_id, 'event_killdate', $event_new_killdate );
update_post_meta( $post_id, 'event_time', $event_new_time );
update_post_meta( $post_id, 'event_location', $event_new_location );
}
}
new events_meta_box;