Posted on by

Showing a Person’s Age in a Record

I get this request a lot, so I thought I’d write up a tutorial on how to do this.

Currently, the only way to do this sort of thing is to write a custom plugin. I know that sounds intimidating to some, but this will be a relatively simple plugin, and I’ll include the code so you don’t even have to write it…although you will have to modify it a little in order for it to work in your particular setup. I’m stressing that because I don’t want anyone to simply install the plugin I’m giving you and then come back and say it doesn’t work!

In this simple plugin, all we’re doing is making sure the field shows the person’s current age. This doesn’t mean you’ll be able to do searching and sorting by age (you have to use the birth date field for that) because the record in the database is only updated with the age value if the record is saved again. Making sure the age value is always current in the record is a bit more complicated, and we won’t be covering that.

Defining the Age Field

First step is to create an age field. Got to the Manage Database Fields page and create up your age field as a plain text field with an appropriate name (I used “age”). Make it read-only since you don’t want to set it manually.

Setting the Age Field’s Value

We will be using the pdb-before_display_form_element filter to set the field’s value in a display context.

In a form context (when the record is getting edited) we use the pdb-form_element_build_{$element} action, which in our case is pdb-form_element_build_text-line because our age field is a simple text line field.

Check the Participants Database API for the details on those filters and actions.

The Plugin

Here is the code, with comments. It will seem fairly complex to those unfamiliar with the use of PHP classes, but all you really need to know is how to edit the values of the two properties (variables) at the top of the class.

Installing the Plugin

To install, go to the Gist page, then click on “Download ZIP” and save the file on your computer. In your WordPress admin, go to the plugins page and install the plugin using the “upload plugin” button.

Once you have it installed, and before you activate it, open the plugin editor (there is an “edit” item in the plugin’s listing on the plugins page) and set the two property values to match your setup. Activate it and you’ll have your age values.

Leave a Reply
You have to agree to the comment policy.

Leave a Reply
You have to agree to the comment policy.