Adding custom fields to content upgrades in the resource library

The resource library template is called resource-library.php. If you’ve looked at this template, you’ll notice it’s an Underscore.js template so you can’t use regular PHP to add custom fields to each content upgrade. A few more steps are required.

First, follow the instructions for editing template files to copy resource-library.php to your child theme. We’ll be editing this later.

Adding your custom fields to the content upgrades array

The first step is to add your extra information to the array of content upgrade data. That’s done with this code snippet:

This code can be placed in your child theme’s functions.php file or in a custom plugin (the latter is recommended).

As noted in the code, the ID of the content upgrade “post” can be accessed using $content_upgrade->ID.

You can use the same format to add as much extra data as you require.

Displaying the information in the template file

Once you’ve added your data to the array, it can be accessed in the Underscore.js template file. You’ll need to follow the syntax described in the wp.template codex article. For example:

  • {{{ }}} – Display unescaped data (if you need to display HTML).
  • {{ }} – Display escaped data.
  • <# #> – Evaluate.

In our previous step, we added a new key to the array named my_custom_field. We’ll need to use this again to display the data, but prefixed with upgrade.. This should be done outside of any <?php tags and inside the _.each loop. Here’s an example:

{{ upgrade.my_custom_field }}

If you want to check if the value isn’t empty first:

<# if ( upgrade.my_custom_field ) { #>
    <p>{{ upgrade.my_custom_field }}</p>
<# } #>

How can we help?