Skip to content

Instantly share code, notes, and snippets.

@Lonsdale201
Created June 10, 2024 19:28
Show Gist options
  • Save Lonsdale201/3e9b3d7584658103fcbd5ae75572440f to your computer and use it in GitHub Desktop.
Save Lonsdale201/3e9b3d7584658103fcbd5ae75572440f to your computer and use it in GitHub Desktop.
JetEngine - JetFormBuilder - Call hook form action - Cron event + CCT user relation query - programmed relation creator
// place the code in the child theme functions.php or a custom code snippets plugin, like FluentSnippets
// What do this code
// In JetFormbuilder, you submit a form that calls a call hook aciton.
// Our code creates a personal cron for each user, which is currently set to a 1 minute run time in the code.
// After this expires, the system will go through all the elements of a given CCT and see
// if the user has any of them associated with a relation. It checks only those that are not already connected,
// then randomly selects one, and programmatically performs a relation connection.
// The code logs everything in the wp log file, so you can review the code from start to finish.
// SETUP YOU NEED FOR THIS CODE TO WORK
// CCT (Custom content type)
// Relation beetween User (parent) CCT (Child) + Register separate DB table enabled
// Only Logged IN user can submit the form!
// SETP 1 In the Jetformbuilder add a new CALL HOOK form action with this Hook name: random-cct-relation
// Create a CCT and change my "house_component" cct slug with your own
// Create some CCT items
// Create a new relation beetween user + CCT (User to parent CCT to child), and enabled the separate db option.
// While you creating the relation in the url check the relation ID (&id=20) and change my 20 with your relation ID
// technically you done. If you do everything good, when submit a form you will see this log:
// [10-Jun-2024 19:18:59 UTC] Cron scheduled for user ID 1: 2024-06-10 21:18:59
// [10-Jun-2024 19:20:35 UTC] Cron started for user ID 1: 2024-06-10 21:20:35
// [10-Jun-2024 19:20:35 UTC] Added CCT item ID 1 to user ID 1 in relation 20
// [10-Jun-2024 19:20:35 UTC] Randomly selected items for user ID 1: CCT house_component item ID: 1
// [10-Jun-2024 19:20:35 UTC] Cron completed for user ID 1: 2024-06-10 21:20:35
// YOU NEED TO KNOW
// Each user can run one cron at a time. But if 10 users run it at the same time, they all get it,
// because crones are personally generated by the code based on the base cron name + user ID,
// so you can run multiple at the same time regardless of the users, but only one for a user at a time.
// Recommended utility plugin to monitor the cron events: https://wordpress.org/plugins/wp-crontrol/
use Jet_Form_Builder\Exceptions\Action_Exception;
/**
* Custom action to initiate a personal cron event when the form is submitted.
*
* @param array $request The form submission data.
* @param object $action_handler The action handler object.
*/
add_action('jet-form-builder/custom-action/random-cct-relation', function($request, $action_handler) {
// Get the current user ID
$current_user_id = get_current_user_id();
if ($current_user_id === 0) {
error_log('User is not logged in.');
return;
}
// Schedule the personal cron job for this user if not already scheduled
// Change the cron hook name here
$hook_name = 'my_custom_cron_hook_' . $current_user_id;
if (!wp_next_scheduled($hook_name, array($current_user_id))) {
// Change the cron interval here (1 minute = 60 seconds for testing)
wp_schedule_single_event(time() + 60, $hook_name, array($current_user_id));
error_log('Cron scheduled for user ID ' . $current_user_id . ': ' . current_time('mysql'));
}
}, 10, 2);
/**
* Register the personal cron event.
*/
add_action('init', function() {
// Get all users with a custom role or capability if needed
$users = get_users();
foreach ($users as $user) {
// Change the cron hook name here
$hook_name = 'my_custom_cron_hook_' . $user->ID;
add_action($hook_name, 'my_custom_cron_function', 10, 1);
}
});
/**
* The function that will be called by the personal cron job.
*
* @param int $user_id The ID of the user for whom the cron job is scheduled.
*/
function my_custom_cron_function($user_id) {
// Log the start of the cron job
error_log('Cron started for user ID ' . $user_id . ': ' . current_time('mysql'));
// Check if JetEngine plugin is installed and active
if (!function_exists('jet_engine')) {
error_log('JetEngine plugin is not installed or activated.');
return;
}
// Check if Custom Content Types module is active
if (!jet_engine()->modules->is_module_active('custom-content-types')) {
error_log('Custom Content Types module is not active.');
return;
}
global $wpdb;
// Change the relation ID here
$relation_id = 20;
// Get the relation object
$relation = jet_engine()->relations->get_active_relations($relation_id);
if (!$relation) {
error_log("Relation ID {$relation_id} not found.");
return;
}
// Get the table name for the relation
$relation_table = $wpdb->prefix . 'jet_rel_' . $relation_id;
// Get the list of CCT items already connected to the user from the database
$connected_items = $wpdb->get_col($wpdb->prepare(
"SELECT child_object_id FROM {$relation_table} WHERE parent_object_id = %d",
$user_id
));
// Get all available CCT types
// Change the CCT slug here if needed
$cct_slug = 'house_component';
$type_object = \Jet_Engine\Modules\Custom_Content_Types\Module::instance()->manager->get_content_types($cct_slug);
if (empty($type_object)) {
error_log('CCT type object not found.');
return;
}
$random_items = [];
$selected_item_id = null;
$handler = $type_object->get_item_handler();
$type_object->db->set_format_flag(\ARRAY_A);
// Get all items
$items = $type_object->db->query(array());
if (empty($items)) {
error_log("No items found in CCT {$cct_slug}.");
return;
}
// Filter out items that are already connected to the user
$filtered_items = array_filter($items, function($item) use ($connected_items) {
return !in_array($item['_ID'], $connected_items);
});
if (empty($filtered_items)) {
error_log("No unconnected items found in CCT {$cct_slug}.");
return;
}
// Randomly select an item
$random_item = $filtered_items[array_rand($filtered_items)];
$item_id = isset($random_item['_ID']) ? $random_item['_ID'] : 'Unknown ID';
$random_items[] = "CCT {$cct_slug} item ID: {$item_id}";
// Select the first random item
if ($selected_item_id === null) {
$selected_item_id = $item_id;
}
if ($selected_item_id !== null) {
// Add the selected CCT item to the user relation
$relation->set_update_context('parent');
$relation->update($user_id, $selected_item_id);
error_log("Added CCT item ID {$selected_item_id} to user ID {$user_id} in relation {$relation_id}");
// Log the selected items
$random_item_log = implode(", ", $random_items);
error_log("Randomly selected items for user ID {$user_id}: {$random_item_log}");
} else {
error_log("No items found to log for user ID {$user_id}");
}
// Log the completion of the cron job
error_log('Cron completed for user ID ' . $user_id . ': ' . current_time('mysql'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment