Created
September 22, 2011 16:23
-
-
Save billerickson/1235232 to your computer and use it in GitHub Desktop.
Limit metabox by page template
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
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']) ; | |
} | |
} | |
} | |
} |
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
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.