Skip to content

Instantly share code, notes, and snippets.

@petenelson
Last active April 4, 2022 17:09
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 petenelson/9ff1cf149540cadbd7865c036ac6ff23 to your computer and use it in GitHub Desktop.
Save petenelson/9ff1cf149540cadbd7865c036ac6ff23 to your computer and use it in GitHub Desktop.
WordPress: Hide specific post editing meta boxes
<?php
$this->_add_action( 'current_screen', 'maybe_hide_meta_boxes' );
/**
* Hides various meta boxes if they have not already been hidden.
* Users can still unhide the meta box and it will not be hidden in
* the future.
*
* @param WP_Screen $screen The current screen object.
*
* @return void
*/
public function maybe_hide_meta_boxes( $screen ) {
if ( empty( $screen->post_type ) ) {
return;
}
// Get a list of meta boxes to hide for this screen (post type).
$metabox_slugs = apply_filters( 'theme_name_hide_meta_boxes_' . $screen->post_type, array(), $screen );
if ( is_array( $metabox_slugs ) ) {
foreach ( array_filter( $metabox_slugs ) as $metabox_slug ) {
$hidden_key = 'theme_name_hidden_' . $metabox_slug . '_' . $screen->post_type;
$hidden = get_user_meta( get_current_user_id(), $hidden_key, true );
if ( empty( $hidden ) ) {
// Hide the meta box for the post type.
$this->hide_meta_box( $screen->post_type, $metabox_slug );
update_user_meta( get_current_user_id(), $hidden_key, '1' );
}
}
}
}
/**
* Hides the meta box for a user and post type.
*
* @param string $post_type The post type.
* @param string $metabox_slug The meta box slug.
* @return void
*/
public function hide_meta_box( $post_type, $metabox_slug ) {
$option = 'metaboxhidden_' . $post_type;
$hidden = get_user_option( $option );
$hidden = ! is_array( $hidden ) ? array() : $hidden;
if ( is_array( $hidden ) ) {
if ( ! in_array( $metabox_slug, $hidden ) ) {
$hidden[] = $metabox_slug;
update_user_option( get_current_user_id(), $option, $hidden, true );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment