0

I've been trying to add a custom meta box in the Edit Page panel for a page using a specific template, in this case front-page.php. I have attempted to use both get_page_template_slug( $post_id ) and get_post_meta( $post_id, '_wp_page_template', true ). But it seems to me that both of these methods merely look for metadata in the database.

Which is a problem, because that's not how my custom template is registered. I've built a custom theme, and I have a page set as the "Front Page", and then a front-page.php file that Wordpress is automatically assigning to said front page. As far as I can tell, there's nothing in the database that says the front page post uses the front-page.php template, which is why the above methods don't work.

So, my question is this: if I have a custom theme with custom page templates that are assigned solely by their filenames, how would I detect those templates so I can add custom meta boxes to their respective Edit Panels?

  • If you already know the pages will be named after the template files, use a switch statement to choose the appropriate metabox based on the page slug or the page title. This is a simple approach but will work. – devkabiir Feb 14 '17 at 7:49
  • The switch statement can be hooked to the add_meta_boxes – devkabiir Feb 14 '17 at 7:52
  • An alternate method will be to create the pages associated with each template file after your theme activation and then saving there page ids, create an object or array out of it and then later you can do something like if arr[my-page] then add this meta box – devkabiir Feb 14 '17 at 8:01
1

The front page configuration is a site option. You can know if the site is configured to display a page with get_option( 'show_on_front' ) and get the ID of the page with get_option( 'page_on_front' ).

You could do something like this:

add_action( 'add_meta_boxes', 'cyb_add_metaboxes', 10, 2 ); 
function cyb_add_metaboxes( $post_type, $post ) {

   if( $post->ID == get_option( 'page_on_front' ) ) {

      add_meta_box('front-page-metabox', 'Front page metabox', 'cyb_front_page_metabox', 'page' );

   }

}

// Metabox callback
function cyb_front_page_metabox() {
}

But with this method, the page needs to be created and assigned to front page before the metabox is rendered. I don't know what kind of data you want to store in the meta fields for the front page, but I think you should explore the customize API, specially if you want to use the metabox for site's front page configuration or site's front page presentational options.

| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.