Wordpress - How to add add_meta_box to specific Page Template?

If your custom page template filename is foobar.php, you can use get_post_meta():

global $post;
if ( 'foobar.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
    // The current page has the foobar template assigned
    // do something
}

Personally, I like calling this inside my add_meta_boxes_page callback, and wrapping it around the add_meta_box() call itself.

function wpse82477_add_meta_boxes_page() {
    global $post;
    if ( 'foobar.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
        add_meta_box( $args );
    }
}
add_action( 'add_meta_boxes_page', 'wpse82477_add_meta_boxes_page' );

You'll just need to instruct users to save the page after assigning the template, so that the meta box appears.


I found a few bugs with the answer above option above but I customized this option below and it helped - no bugs at all.

add_action('add_meta_boxes', 'add_product_meta');
function add_product_meta()
{
    global $post;

    if(!empty($post))
    {
        $pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);

        if($pageTemplate == 'page-templates/product-page.php' )
        {
            add_meta_box(
                'product_meta', // $id
                'Product Information', // $title
                'display_product_information', // $callback
                'page', // $page
                'normal', // $context
                'high'); // $priority
        }
    }
}

function display_product_information()
{
    // Add the HTML for the post meta
}

https://paulund.co.uk/display-post-meta-box-specific-page-templates

It's clean