MetaBox – Certificate
class mb_certificate {
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(
'certificate_details',
__( 'Zertifikate', 'text_domain' ),
array( $this, 'render_metabox' ),
'pt_certificate',
'advanced',
'default'
);
}
public function render_metabox( $post ) {
// Retrieve an existing value from the database.
$certificate_url = get_post_meta( $post->ID, 'certificate_url', true );
$certificate_runtime = get_post_meta( $post->ID, 'certificate_runtime', true );
// Set default values.
if( empty( $certificate_url ) ) $certificate_url = '';
if( empty( $certificate_runtime ) ) $certificate_runtime = '';
// Form fields.
echo '<table class="form-table">';
echo ' <tr>';
echo ' <th><label for="certificate_url" class="certificate_url_label">' . __( 'Homepage', 'text_domain' ) . '</label></th>';
echo ' <td>';
echo ' <input type="url" id="certificate_url" name="certificate_url" class="certificate_url_field" placeholder="' . esc_attr__( '', 'text_domain' ) . '" value="' . esc_attr( $certificate_url ) . '">';
echo ' <p class="description">' . __( 'Homepage der Auszeichnung oder der Zertifikats', 'text_domain' ) . '</p>';
echo ' </td>';
echo ' </tr>';
echo ' <tr>';
echo ' <th><label for="certificate_runtime" class="certificate_runtime_label">' . __( 'Laufzeit', 'text_domain' ) . '</label></th>';
echo ' <td>';
echo ' <input type="date" id="certificate_runtime" name="certificate_runtime" class="certificate_runtime_field" placeholder="' . esc_attr__( '', 'text_domain' ) . '" value="' . esc_attr( $certificate_runtime ) . '">';
echo ' <p class="description">' . __( 'Laufzeit des Zertifikats', 'text_domain' ) . '</p>';
echo ' </td>';
echo ' </tr>';
echo '</table>';
}
public function save_metabox( $post_id, $post ) {
// Check if the user has permissions to save data.
if ( ! current_user_can( 'edit_post', $post_id ) )
return;
// Sanitize user input.
$certificate_new_url = isset( $_POST[ 'certificate_url' ] ) ? esc_url( $_POST[ 'certificate_url' ] ) : '';
$certificate_new_runtime = isset( $_POST[ 'certificate_runtime' ] ) ? sanitize_text_field( $_POST[ 'certificate_runtime' ] ) : '';
// Update the meta field in the database.
update_post_meta( $post_id, 'certificate_url', $certificate_new_url );
update_post_meta( $post_id, 'certificate_runtime', $certificate_new_runtime );
}
}
new mb_certificate;