Programmatically add data to WordPress Participants Database using PHP

Programmatically add data to WordPress Participants Database using PHP

The Participants Database WordPress plugin has come in handy on a number of projects for me as a WordPress database that can easily be hooked into and data exported.

Recently I came across a project whereby I needed to add data dynamically via an AJAX call but first I needed to check if the data exists.

I thought I would share this with you guys to see if it helped in any way.

First we want to ensure that the Participants Database plugin is active by using:

if ( class_exists('Participants_Db') ) {

// Run code

}

In my case, I was checking if the record existed already as I only wanted to write the data if it wasn’t there already, you may or may not need this here:

$existsRecord = Participants_Db::get_record_id_by_term(’email’, $email, $single = true);

if (empty($existsRecord)) {

//Record doesn't exist, lets run our code!

}

As you can see, this is simple enough. Next I am pulling the data through POST as this is an AJAX call, you may have a different method for this but either way, we need to put the data we want to write in an Array where the keys correspond to the column names in our database:

$participantData = array();
$participantData['full_name'] = $name;
$participantData['email'] = $email;
$participantData['age'] = $age;

So now we have our data we just need to write it to the database and this is incredibly easy to do with one line of code:

Participants_Db::write_participant( $participantData );

So all we are doing it hooking into the write_participant() function from the Participants_Db class.

All the code put together as follows:

if ( class_exists('Participants_Db') ) {

$existsRecord = Participants_Db::get_record_id_by_term('email', $email, $single = true);

if (empty($existsRecord)) {

$participantData = array();
$participantData['full_name'] = $name;
$participantData['email'] = $email;
$participantData['age'] = $age;

Participants_Db::write_participant( $participantData );

}

}

I hope this has been of some help to some of you, let me know in the comments how you got on!

Menu Title