Owl Button Metabox
class Owl_Button_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(
'owl_button',
__( 'Owl Button', 'text_domain' ),
array( $this, 'render_metabox' ),
'owl_post_type',
'side',
'core'
);
}
public function render_metabox( $post ) {
// Retrieve an existing value from the database.
$owlbutton_button-text = get_post_meta( $post->ID, 'owlbutton_button-text', true );
$owlbutton_button-url = get_post_meta( $post->ID, 'owlbutton_button-url', true );
// Set default values.
if( empty( $owlbutton_button-text ) ) $owlbutton_button-text = '';
if( empty( $owlbutton_button-url ) ) $owlbutton_button-url = '';
// Form fields.
echo '<table class="form-table">';
echo ' <tr>';
echo ' <th><label for="owlbutton_button-text" class="owlbutton_button-text_label">' . __( 'Button Text', 'text_domain' ) . '</label></th>';
echo ' <td>';
echo ' <input type="text" id="owlbutton_button-text" name="owlbutton_button-text" class="owlbutton_button-text_field" placeholder="' . esc_attr__( '', 'text_domain' ) . '" value="' . esc_attr__( $owlbutton_button-text ) . '">';
echo ' <p class="description">' . __( 'Leave blank to disable button', 'text_domain' ) . '</p>';
echo ' </td>';
echo ' </tr>';
echo ' <tr>';
echo ' <th><label for="owlbutton_button-url" class="owlbutton_button-url_label">' . __( 'Button URL', 'text_domain' ) . '</label></th>';
echo ' <td>';
echo ' <input type="url" id="owlbutton_button-url" name="owlbutton_button-url" class="owlbutton_button-url_field" placeholder="' . esc_attr__( '', 'text_domain' ) . '" value="' . esc_attr__( $owlbutton_button-url ) . '">';
echo ' </td>';
echo ' </tr>';
echo '</table>';
}
public function save_metabox( $post_id, $post ) {
// Sanitize user input.
$owlbutton_new_button-text = isset( $_POST[ 'owlbutton_button-text' ] ) ? sanitize_text_field( $_POST[ 'owlbutton_button-text' ] ) : '';
$owlbutton_new_button-url = isset( $_POST[ 'owlbutton_button-url' ] ) ? esc_url( $_POST[ 'owlbutton_button-url' ] ) : '';
// Update the meta field in the database.
update_post_meta( $post_id, 'owlbutton_button-text', $owlbutton_new_button-text );
update_post_meta( $post_id, 'owlbutton_button-url', $owlbutton_new_button-url );
}
}
new Owl_Button_Meta_Box;