Last active
April 4, 2022 17:09
-
-
Save petenelson/9ff1cf149540cadbd7865c036ac6ff23 to your computer and use it in GitHub Desktop.
WordPress: Hide specific post editing meta boxes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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