Undefined function error when creating Custom Meta Box

Following this tutorial, I am trying to create a custom Meta Box on my theme by adding following codes to the function.php file:

add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );
add_action( 'add_meta_boxes', 'cd_meta_box_add' );

function cd_meta_box_add()
{
  add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );
}

function cd_meta_box_cb()  
{  
  echo 'What you put here, show's up in the meta box';     
}  

but I am getting following error :

Read More

fatal error

( ! ) Fatal error: Call to undefined function add_meta_box() in C:wampwwwTMPresswp-contentthemestwentytwelvecpt.php on line 94
Call Stack
#   Time    Memory  Function    Location
1   0.0012  865440  {main}( )   ..edit.php:0
2   0.0018  982824  require_once( 'C:wampwwwTMPresswp-adminadmin.php' )    ..edit.php:10
3   0.0021  1008744 require_once( 'C:wampwwwTMPresswp-load.php' )   ..admin.php:30
4   0.0023  1026872 require_once( 'C:wampwwwTMPresswp-config.php' ) ..wp-load.php:29
5   0.0029  1158248 require_once( 'C:wampwwwTMPresswp-settings.php' )   ..wp-config.php:90
6   0.3251  32951888    include( 'C:wampwwwTMPresswp-contentthemestwentytwelvefunctions.php' )   ..wp-settings.php:291
7   0.3255  32979176    include_once( 'C:wampwwwTMPresswp-contentthemestwentytwelvecpt.php' )    ..functions.php:2

Can you please let me know why this is happening? is there any better way to add a meta box containing a field and dropdown select box? I know there are some plugins out there for doing this but I really like to learn it on my own.

Related posts

1 comment

  1. Try this

    add_action( 'add_meta_boxes', 'cd_meta_box_add' );
    
    function cd_meta_box_add()
    {
      add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );
    }
    
    function cd_meta_box_cb()  
    {  
      echo 'What you put here, show's up in the meta box';     
    }  
    

    ps: you have some extra problematic lines, at the top of your code, that I removed, namely:

    add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );
    

    Update:

    To add the metabox to your custom post type edit page, replace 'post' with 'your-custom-post-type' in this line:

    add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'your-custom-post-type', 'normal', 'high' );
    

Comments are closed.