I am trying to add custom metaboxes to only those pages that use a certain custom template that is applied to them.

How can i do this? I based on this this guide: How to add add_meta_box to specific Page Template?

But it doesn't work for me. How come?

This is my code in functions.php:

add_action("admin_init", "metabox_bookmaker");
function metabox_bookmaker(){
    global $post;
    if ( 'page-templates/template-bookmaker.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
        add_meta_box("metabox_bookmaker_custom", "Metabox per Single Bookmaker", "custom_metabox_bookmaker", "page", "normal", "high");
  • Meta boxes should be added using the add_meta_boxes hook or post-type-specific hooks like add_meta_boxes_page. And with these hooks, you'd get the correct post object for the current post without having to access the $post global. – Sally CJ Jun 15 at 12:15
  • 1
    Great, thank you so much, I was almost there, but your response anticipated and confirmed what I was thinking. Now it works! – Matteo Feduzi Jun 15 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.