Skip to content

Instantly share code, notes, and snippets.

@codigoconjuan
Created June 30, 2015 21:57
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 codigoconjuan/7bd2aa56a01e8a27c78c to your computer and use it in GitHub Desktop.
Save codigoconjuan/7bd2aa56a01e8a27c78c to your computer and use it in GitHub Desktop.
add_action( 'cmb2_init', 'show_on_page_template' );
/**
* Hook in and add a metabox to demonstrate repeatable grouped fields
*/
function show_on_page_template() {
$cmb = new_cmb2_box( array(
'id' => 'contact-information',
'title' => 'Contact Information',
'show_on' => array( 'key' => 'page-template', 'value' => 'page-nosidebar.php' ),
'context' => 'normal', // 'normal', 'advanced', or 'side'
'priority' => 'high', // 'high', 'core', 'default' or 'low'
'show_names' => true, // Show field names on the left
) );
$cmb->add_field( array(
'name' => 'Testing Field Parameters',
'id' => $prefix . 'parameters',
'type' => 'text',
'before_row' => 'yourprefix_before_row_if_2', // callback
'before' => '<p>Testing <b>"before"</b> parameter</p>',
'before_field' => '<p>Testing <b>"before_field"</b> parameter</p>',
'after_field' => '<p>Testing <b>"after_field"</b> parameter</p>',
'after' => '<p>Testing <b>"after"</b> parameter</p>',
'after_row' => '<p>Testing <b>"after_row"</b> parameter</p>',
) );
}
/**
* Metabox for Page Template
* @author Kenneth White
* @link https://github.com/WebDevStudios/CMB2/wiki/Adding-your-own-show_on-filters
*
* @param bool $display
* @param array $cmb
* @return bool display metabox
*/
function be_metabox_show_on_template( $display, $cmb ) {
if ( ! isset( $cmb['show_on']['key'], $cmb['show_on']['value'] ) ) {
return $display;
}
if ( 'page-nosidebar.php' !== $cmb['show_on']['key'] ) {
return $display;
}
$post_id = 0;
// 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 ( ! $post_id ) {
return false;
}
$template_name = get_page_template_slug( $post_id );
$template_name = ! empty( $template_name ) ? substr( $template_name, 0, -4 ) : '';
// See if there's a match
return in_array( $template_name, (array) $cmb['show_on']['value'] );
}
add_filter( 'cmb2_show_on', 'be_metabox_show_on_template', 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment