Skip to content

Instantly share code, notes, and snippets.

@pixelwatt
Last active June 2, 2017 08:27
Show Gist options
  • Save pixelwatt/304f09ab1809c49d7ab978a1b85db826 to your computer and use it in GitHub Desktop.
Save pixelwatt/304f09ab1809c49d7ab978a1b85db826 to your computer and use it in GitHub Desktop.
CMB2 show_on Filter for Default Page Template
<?php
/**
* Include metabox only on the default page template (page.php). Heavily based of Ed Townend's front-page solution
* @author Rob Clark
*
* @param bool $display
* @param array $meta_box
* @return bool display metabox
*/
function cmb2_metabox_include_default_page( $display, $meta_box ) {
if ( ! isset( $meta_box['show_on']['key'] ) ) {
return $display;
}
if ( 'default-page-template' !== $meta_box['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;
}
$page_template = get_page_template_slug( $post_id );
if ( empty($page_template) ) {
$is_it_basic = true;
} else {
$is_it_basic = false;
}
// there is a front page set and we're on it!
return $is_it_basic;
}
add_filter( 'cmb2_show_on', 'cmb2_metabox_include_default_page', 10, 2 );
/**
* Example Usage:
*
* $cmb_page_default_options = new_cmb2_box( array(
* 'id' => $prefix . 'metabox',
* 'title' => __( 'Default Page Template Options', 'mytheme' ),
* 'object_types' => array( 'page' ),
* 'show_on' => array( 'key' => 'default-page-template', 'value' => '' ),
* ) );
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment