Skip to content

Instantly share code, notes, and snippets.

@jeffreyvr
Last active October 26, 2020 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffreyvr/757df2027f04191c54ce02c7ced35abc to your computer and use it in GitHub Desktop.
Save jeffreyvr/757df2027f04191c54ce02c7ced35abc to your computer and use it in GitHub Desktop.
Boilerplate meta box
<?php
/**
* Class.
*
* @package a-package
*/
/**
* Class.
*/
class Prefix_Page_Meta_Box {
/**
* Constructor.
*/
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'register' ), 10, 1 );
add_action( 'save_post', array( $this, 'save' ), 10, 2 );
}
/**
* Register
*
* @param WP_Post $post The current post.
* @return void
*/
public function register( $post ) {
add_meta_box( 'prefix_page_meta_box', __( 'Page details', 'text-domain' ), array( $this, 'html' ), 'page' );
}
/**
* Save.
*
* @param int $post_id The post id.
* @param WP_Post $post The post object.
* @return void
*/
public function save( $post_id, $post ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( ! isset( $_POST['prefix_page_meta_box_nonce'] ) || ! wp_verify_nonce( $_POST['prefix_page_meta_box_nonce'], basename( __FILE__ ) ) ) {
return $post_id;
}
$post_type = get_post_type_object( $post->post_type );
if ( ! current_user_can( $post_type->cap->edit_post, $post_id ) ) {
return $post_id;
}
$meta_keys = array(
'prefix_example_1' => FILTER_SANITIZE_STRING,
'prefix_example_2' => FILTER_SANITIZE_STRING
);
foreach ( $meta_keys as $meta_key => $filter ) {
if ( ! empty( $_POST[ $meta_key ] ) ) {
if ( $filter === 'array' || $filter === null ) {
update_post_meta( $post_id, '_' . $meta_key, $_POST[ $meta_key ] );
} else {
update_post_meta( $post_id, '_' . $meta_key, filter_input( INPUT_POST, $meta_key, $filter ) );
}
} else {
delete_post_meta( $post_id, '_' . $meta_key );
}
}
}
/**
* HTML.
*
* @param WP_Post $post The WordPress post object.
* @return void
*/
public function html( $post ) {
$example_1 = get_post_meta( $post->ID, '_prefix_example_1', true );
$example_2 = get_post_meta( $post->ID, '_prefix_example_2', true );
wp_nonce_field( basename( __FILE__ ), 'prefix_page_meta_box_nonce' );
?>
<p>
<label for="prefix_example_1"><?php _e( 'Example 1', 'text-domain' ); ?></label>
<?php wp_editor( $example_1, 'prefix_example_1' ); ?>
</p>
<p>
<label for="prefix_example_2"><?php _e( 'Example 2', 'text-domain' ); ?></label>
<input type="text" id="prefix_example_2" name="prefix_example_2" value="<?php echo esc_attr( $example_2 ); ?>">
</p>
<?php
}
}
new Prefix_Page_Meta_Box();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment