I’m trying to make change to a site where with the current infrastructure isn’t great as due to how it’s been built over the previous site rather then fresh.
I have a section of the site which needs it’s own custom fields. This section doesn’t warrant it’s own post type, and due to the state of the site it’s extremely impractical to do it this way. What I don’t want for the sake of the user is to have to make them use the custom fields as it’s pretty sloppy.
So, how can I add fields (like you would for a custom post type) when a certain template is selected?
Can you do that? Absolutely! You simply need to query the
_wp_page_template
meta key value of the$post
object, and act accordingly. Perhaps something like so:Now, I would recommend using a custom post meta box, rather than custom fields.
While full implementation of custom post meta boxes is slightly outside the scope of your question, the underlying answer remains the same. I’ll try to point you in the general direction, though. You’ll use a combination of
add_meta_box()
, called in a callback hooked intoadd_meta_boxes-{hook}
, a callback to define the metabox, and a callback to validate/sanitize and save custom post meta.Edit
It may be better to wrap the entire
add_meta_box()
call in the conditional.