Skip to content

Instantly share code, notes, and snippets.

@billerickson
Created September 22, 2011 16:23
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 billerickson/1235232 to your computer and use it in GitHub Desktop.
Save billerickson/1235232 to your computer and use it in GitHub Desktop.
Limit metabox by page template
Limit Metabox by Page Template
To test, go into init.php and replace the add() function with the one below. Then, add the following to a metabox array:
'show_on' => array( 'key' => 'page-template', 'value' => 'template-name.php' ),
Of course, replacing template-name.php with your template's file name.
<?php
// Add metaboxes
function add() {
$this->_meta_box['context'] = empty($this->_meta_box['context']) ? 'normal' : $this->_meta_box['context'];
$this->_meta_box['priority'] = empty($this->_meta_box['priority']) ? 'high' : $this->_meta_box['priority'];
foreach ( $this->_meta_box['pages'] as $page ) {
if( !isset( $this->_meta_box['show_on'] ) ) {
add_meta_box( $this->_meta_box['id'], $this->_meta_box['title'], array(&$this, 'show'), $page, $this->_meta_box['context'], $this->_meta_box['priority']) ;
} else {
if ( 'id' == $this->_meta_box['show_on']['key'] ) {
// If we're showing it based on ID, get the current ID
if( isset( $_GET['post'] ) ) $post_id = $_GET['post'];
elseif( isset( $_POST['post_ID'] ) ) $post_id = $_POST['post_ID'];
// If current page id is in the included array, display the metabox
if ( isset( $post_id) && in_array( $post_id, $this->_meta_box['show_on']['value'] ) )
add_meta_box( $this->_meta_box['id'], $this->_meta_box['title'], array(&$this, 'show'), $page, $this->_meta_box['context'], $this->_meta_box['priority']) ;
} elseif( 'page-template' == $this->_meta_box['show_on']['key'] ) {
// Get the current ID
if( isset( $_GET['post'] ) ) $post_id = $_GET['post'];
elseif( isset( $_POST['post_ID'] ) ) $post_id = $_POST['post_ID'];
if( !( isset( $post_id ) || is_page() ) ) return;
// Get current template
$current_template = get_post_meta( $post_id, '_wp_page_template', true );
// See if there's a match
if( $current_template == $this->_meta_box['show_on']['value'] )
add_meta_box( $this->_meta_box['id'], $this->_meta_box['title'], array(&$this, 'show'), $page, $this->_meta_box['context'], $this->_meta_box['priority']) ;
}
}
}
}
@billerickson
Copy link
Author

It's working just fine on the client project I'm working on, but I'd like a bit more testing before I add it to core.

@billerickson
Copy link
Author

Added line 33 to make sure we have an ID and are on a post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment