Skip to content

Instantly share code, notes, and snippets.

@xnau
Last active February 7, 2024 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnau/8f0be1456e918bcf39142ea11c2844c5 to your computer and use it in GitHub Desktop.
Save xnau/8f0be1456e918bcf39142ea11c2844c5 to your computer and use it in GitHub Desktop.
Shows how to update Participants Database calculated field using a cron.
<?php
/**
* Plugin Name: PDB Dynamic Field Cron Updater
* Description: updates dynamic fields automatically on a WP cron
* Version: 1.0
*/
class PDb_Dynamicfield_Cron_Updater
{
/**
* @param string name of the cron hook
*/
private $hook = 'xnau_dynfield_update';
/**
* sets up the cron and actions
*/
public function __construct()
{
// use this function to reset the cron
// useful if you need to change the time it runs
// remember to comment it out again after
//$this->unschedule();
// this sets up the method that is called when our cron runs
add_action( $this->hook, [$this,'dynamic_db_field_update'] );
/*
* this sets the daily cron time to 12pm
*
* IMPORTANT: normally, the WP cron is run when someone visits the site,
* therefore if your site is not getting much traffic, the cron probably
* won't run on time.
*
* There are many examples of how to set up the WP cron to run without
* needing the site visit to trigger it, for example:
* https://www.siteground.com/tutorials/wordpress/real-cron-job/
*/
$time_of_day = strtotime('2024-02-07 12:00:00');
if ( ! wp_next_scheduled( $this->hook ) )
{
// this sets up the WP cron to trigger our action daily at the time set above
wp_schedule_event( $time_of_day, 'daily', $this->hook );
}
}
/**
* update a dynamic db field value
*
* this will process an update for all dynamic fields for all records
*/
public function dynamic_db_field_update()
{
$id_list = Participants_Db::get_id_list([]); // gets all record ids
foreach( $id_list as $id )
{
$record = Participants_Db::get_participant( $id );
if ( ! is_array( $record ) )
{
// if the id doesn't pull up a record, skip to the next one
continue;
}
$this->update_record( $record );
}
}
/**
* updates a new record
*
* @param array $record the new record submission values
*/
private function update_record( $record )
{
// update the dynamic values in the record
$updated_record = apply_filters( 'pdb-dynamic_db_field_update', $record );
// filter out any values that did not change
$post = array_diff_assoc( $updated_record, $record );
if ( ! empty( $post ) )
{
// if we have changed values, write them to the database
Participants_Db::write_participant( $post, $record['id'] );
}
}
/**
* unschedules the cron
*/
private function unschedule()
{
$timestamp = wp_next_scheduled( $this->hook );
wp_unschedule_event( $timestamp, $this->hook );
}
}
new PDb_Dynamicfield_Cron_Updater();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment