Last active
February 11, 2024 04:43
-
-
Save xnau/87a1f006155b6017ffced94c5e63973d to your computer and use it in GitHub Desktop.
Shows how to update single Participants Database dynamic field triggered by a cron
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: PDB Dynamic Field Cron Updater Version 2 | |
* Description: updates a dynamic field automatically on a WP cron | |
* Version: 2.0 | |
*/ | |
class PDb_Dynamicfield_Cron_Updater2 | |
{ | |
/** | |
* @param string name of the cron hook | |
*/ | |
private $hook = 'xnau_dynfield_update'; | |
/** | |
* @param string name of the field to update | |
*/ | |
private $fieldname = 'age'; | |
/** | |
* 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 2pm | |
* | |
* 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 14: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 a dynamic db field for all records | |
* | |
* @return int number of records updated | |
*/ | |
public function dynamic_db_field_update() | |
{ | |
do_action( 'pdb-dynamic_db_field_update_all', $this->fieldname, [] ); | |
} | |
/** | |
* unschedules the cron | |
*/ | |
private function unschedule() | |
{ | |
$timestamp = wp_next_scheduled( $this->hook ); | |
wp_unschedule_event( $timestamp, $this->hook ); | |
} | |
} | |
new PDb_Dynamicfield_Cron_Updater2(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This requires Participants Database Version 2.5.7 or later to work.
This is to be installed as a plugin. You should set the name of the field that you want to update on line 19.
This plugin uses a background process to update all records, so it won't time out of there are a large number of records to process.