Adding custom fields to a custom page template in WordPress

If you're building WordPress up as CMS you'll quickly find yourself needing the ability to add custom fields to custom templates. You can of course do this by default in the admin panel, but each time you create a new page you need to manually type in all the custom field types - not great for your end-users. What would be better is if all the custom fields associated with a specifc template show as options when the template is selected. 

Here's how you can do it...

Install advanced custom fields plugin

To achieve our goal we'll be installing a plugin called 'Advanced Custom Fields'. The plugin allows you to do a lot more with custom fields than just assign them to page templates, but this is what we'll be focussing on in this post.

Install the 'Advanced Custom Fields' plugin found here:

or by searching in the plugins section for 'advanced custom fields' under 'Add new'. After installation click to 'Activate' the plugin. You'll now see that 'Custom fields' has been added to the bottom of your admin menu. 

Assign some custom fields to a custom template

In a previous blog article we looked at how to create custom page templates. We're now going to assign some custom fields to a template described in that article. 

  • Click on 'Custom Fields' on the left hand admin menu
  • Click 'Add new'
  • Under 'Location' set the rule to 'Page Template' is 'Equal to' 'My custom template'
  • Above the location section click 'Add field' and enter the field name. For this demonstration we'll call the field name 'custom_about' with a field type of 'wysiwig editor'
  • Give the field group a name at the top, in this demo I've called it 'Extra'
  • Click 'Publish' on the right hand side

If you go to one of your pages now and select your custom template, you'll notice that the additional custom fields are available. 

Accessing the custom fields in your template

You can access your new fields using the following snippet ('about' being our new custom field):

    echo get_post_meta($post->ID, 'about', true)

The 'get_post_meta' takes three arguments; the id of the post / page, the key for the custom field name and if you are expecting an array of results or a single result. 

Sign Up
comments powered by Disqus

Popular Tags

Need a web developer?

If you'd like to work with code synthesis on your next project get in touch via the contact page.