KBNT – portfolio – cmb
class cmb_portfolio {
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(
'others',
__( 'Další informace k položce v portfoliu', 'kybernaut' ),
array( $this, 'render_metabox' ),
'portfolio',
'normal',
'default'
);
}
public function render_metabox( $post ) {
// Add nonce for security and authentication.
wp_nonce_field( 'kbnt_nonce_action', 'kbnt_nonce' );
// Retrieve an existing value from the database.
$kbnt_url = get_post_meta( $post->ID, 'kbnt_url', true );
$kbnt_reference = get_post_meta( $post->ID, 'kbnt_reference', true );
// Set default values.
if( empty( $kbnt_url ) ) $kbnt_url = '';
if( empty( $kbnt_reference ) ) $kbnt_reference = '';
// Form fields.
echo '<table class="form-table">';
echo ' <tr>';
echo ' <th><label for="kbnt_url" class="kbnt_url_label">' . __( 'URL', 'kybernaut' ) . '</label></th>';
echo ' <td>';
echo ' <input type="url" id="kbnt_url" name="kbnt_url" class="kbnt_url_field" placeholder="' . esc_attr__( '', 'kybernaut' ) . '" value="' . esc_attr__( $kbnt_url ) . '">';
echo ' </td>';
echo ' </tr>';
echo ' <tr>';
echo ' <th><label for="kbnt_reference" class="kbnt_reference_label">' . __( 'Reference', 'kybernaut' ) . '</label></th>';
echo ' <td>';
wp_dropdown_pages( array( 'id' => 'kbnt_reference', 'name' => 'kbnt_reference', 'class' => 'kbnt_reference_field', 'selected' => $kbnt_reference ) );
echo ' </td>';
echo ' </tr>';
echo '</table>';
}
public function save_metabox( $post_id, $post ) {
// Add nonce for security and authentication.
$nonce_name = isset( $_POST['kbnt_nonce'] ) ? $_POST['kbnt_nonce'] : '';
$nonce_action = 'kbnt_nonce_action';
// Check if a nonce is set.
if ( ! isset( $nonce_name ) )
return;
// Check if a nonce is valid.
if ( ! wp_verify_nonce( $nonce_name, $nonce_action ) )
return;
// Check if the user has permissions to save data.
if ( ! current_user_can( 'edit_post', $post_id ) )
return;
// Check if it's not an autosave.
if ( wp_is_post_autosave( $post_id ) )
return;
// Check if it's not a revision.
if ( wp_is_post_revision( $post_id ) )
return;
// Sanitize user input.
$kbnt_new_url = isset( $_POST[ 'kbnt_url' ] ) ? esc_url( $_POST[ 'kbnt_url' ] ) : '';
$kbnt_new_reference = isset( $_POST[ 'kbnt_reference' ] ) ? sanitize_text_field( $_POST[ 'kbnt_reference' ] ) : '';
// Update the meta field in the database.
update_post_meta( $post_id, 'kbnt_url', $kbnt_new_url );
update_post_meta( $post_id, 'kbnt_reference', $kbnt_new_reference );
}
}
new cmb_portfolio;