Participants Database 1.5 has a new utility class that was created to make templating much easier. The default templates used by the plugin are based on loops, much like the standard WordPress templates. Loops are the best way to deal with a situation where you don’t know the number of fields to be shown: the template just keeps showing fields in a repeating pattern until they have all been displayed. Loops are also an efficient way to represent many similar pieces of content.
That may be convenient, but displaying data in a meaningful way often demands you treat parts of the dataset differently. Some of those fields are just more important than others, or perhaps some pieces need to be arranged on the page in a way that best suits the content.
The PDb_Template Class
The PDb_Template class adds several convenient methods for displaying the data in a record. The class is instantiated once for each record, so if the page is a single record, this happens once at the top of the template. For a list of records, the class is instantiated in the loop after the record has been read from the database. I’ll show you an example of a single record template that uses the PDb_Template class for it’s layout.
This template takes several of the more important pieces of information from the record and presents it in a much more readable format. Other fields are logically laid out in groups below that. Below all that, the remaining fields are shown using a shortcode that prints a loop of the groups those fields are in.
This template starts with the instantiation of the Template class near the top, before anything is output. With that, the variable $this_business has all the data of the current record, as well as several convenient functions to help you set up your template.
The main method you will use is
print_field('field_name'). Just give it the name of the field you want to print and the method will echo the value formatted for display. It’s mostly self-explanatory.
Raw values are available for calculations or custom formatting using the
get_value('field_name') method, demonstrated where we show the number of years the business has been around. Dates are stored as UNIX timestamps, so the raw values from that field needs to be converted to a year for the calculation.
A method named
has_content('field_name') can be used to skip over fields that are empty. You see that in use where we want to show the photograph if it exists.
At the end of the template, we use the WP function
do_shortcode() to print out the rest of the fields, which are contained in the “More Details” field group. This shortcode uses a special template designed for this purpose: it just does not print the wrapper div because it will appear inside one.
There are a few more convenient methods you can use, which I will demonstrate in the next tutorial on using the PDb_Template utility class.