I'm building a custom theme and I want to create a helper class for handling creation of metaboxes in admin panel. I have my class declared like this:
namespace ci\wp;
Metaboxes::init();
class Metaboxes {
private static $instance;
private static $post;
private static $metaboxesPath = TEMPLATEPATH . "/config/metaboxes/";
static function init() {
global $post;
self::$post = &$post;
add_action( 'add_meta_boxes', [ __CLASS__, 'addMetabox' ], 10, 5 );
}
// ADD METABOX
static function addMetabox($id, $title, $post_type, $position, $priority) {
if (file_exists(self::$metaboxesPath.$id.'.php')) {
require_once(self::$metaboxesPath.$id.'.php');
add_meta_box($id, $title, 'do_'.$id, $post_type, $position, $priority);
}
}
[...]
The problem is that when I want to use the addMetabox method, by writing \ci\wp\Metaboxes::addMetabox('front_page_slide_settings', 'Slide settings', 'page', 'normal', 'high');
I get the following error:
Fatal error: Uncaught Error: Call to undefined function ci\wp\add_meta_box() in [...]
I tried several different methods of using add_action inside the class but no matter if it's a static class, singleton with add_action run at instantiation or a normal class with add_action in constructor, it always results in the said error.
Is there a way to make it work? What am I doing wrong?
add_meta_box
function call should be hooked to theadd_meta_boxes
hook. You can either have an array with all desired metabox settings and then run a loop through the array, insideaddMetabox
that is hook toadd_meta_boxes
hook, and calladd_meta_box
with the settings as input or every time you calladdMetabox
you add an action.