• rss icon

Blog

How to Create a Conditional Meta Box in WordPress

Have you ever want to have a meta box that only display when editing a pages that uses a particular template? That is not difficult to do if you can determine what template the page is using. This can be done with this code:

$post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ;
$template_file = get_post_meta($post_id,'_wp_page_template',TRUE);

Now we can call our functions to create and save meta box values while that check the current template in use within our functions.php:

function sm_meta_box_add()
{
  // get the template file name
  $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ;
  $template_file = get_post_meta($post_id,'_wp_page_template',TRUE);
  
  if ($template_file == 'my-template_name.php') {
	  add_meta_box( 'sm-meta-box-id', 'Meta box Name', 'sm_meta_box_items', 'page', 'normal', 'high' );
  }  
}

add_action( 'add_meta_boxes', 'sm_meta_box_add' );

function sm_meta_box_items() {
	global $post;
  
  // your mete box code

}

function save_sm_meta_fields ( $post_id )
{
  $template_file = get_post_meta($post_id,'_wp_page_template',TRUE);
  
  if ($template_file == 'my-template_name.php') {
    
    // code to save meta box values
  }
}

add_action('save_post', 'save_sm_meta_fields', 20, 2);

That’s all there is to it.

View or download this code on GitHub