English (United Kingdom)
Knowledge Base  >  Vik Booking  >  For Developers  >  Custom Cron Jobs

do_action( 'vikbooking_create_cron_jobs_factory', VBOCronFactory $factory )

Fires during the registration/loading of the driver files for each available Cron Job in Vik Booking.


Description

Plugins can use this filter to install at runtime one or more custom Cron Jobs for Vik Booking.

The registered Cron Jobs will be available in the wp-admin section for the setup and execution scheduling through WP-Cron. Please notice this is how to register/install custom Cron Jobs, but each driver file will require to declare its own class (more information below).


Parameters

$factory

(VBOCronFactory)  The Cron Factory object of Vik Booking.


Example

The example below shows how to register additional Cron Jobs in Vik Booking to perform specific tasks through apposite driver files.

The code is adding a path for including new Cron Jobs, and so any valid PHP driver file inside the directory "crons" of this plugin will be loaded as a new Cron Job. That directory should be next to the main plugin file:

/wp-content/plugins/custom-cron-jobs/custom-cron-jobs.php
/wp-content/plugins/custom-cron-jobs/crons/
/**
 * Trigger action to let Vik Booking install every custom Cron Job inside the
 * "crons" directory of this plugin. This is just an example of how you can 
 * register custom Cron Job driver files into Vik Booking.
 * 
 * @param   VBOCronFactory  $factory    the Cron Factory object of Vik Booking.
 */
add_action('vikbooking_create_cron_jobs_factory', function(VBOCronFactory $factory)
{
    // let Vik Booking register every custom cron job inside this directory
    $factory->addIncludePath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'crons');

});

Now it's time to actually create the driver file for each custom Cron Job you want to install. Each driver file is responsible for declaring the Cron Job PHP class file, defining its settings and executing the actual task.

The PHP driver file of the custom Cron Job will have to be placed in the below plugin's directory. The file name will also affect the name of the PHP class the driver should declare, or your Cron Job won't be loaded at all:

/wp-content/plugins/custom-cron-jobs/crons/sample_task.php
<?php
/**
 * @package     VikBooking
 * @subpackage  custom-cron-job.sample_task
 * @author      E4J srl (VikWP)
 * @copyright   Copyright (C) 2023 E4J srl. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE
 * @link        https://vikwp.com
 */

defined('ABSPATH') or die('No script kiddies please!');

/**
 * This is a copy/clone of the native "Email Reminder" Cron Job.
 * Just the file name, the class name and the Cron title are different.
 * You can do the same to create your custom Cron Job driver file to
 * execute specific tasks.
 */
class VikBookingCronJobSampleTask extends VBOCronJob
{
    // use this Trait when you don't need to keep track of any
    // bookings/customers that were notified by the Cron Job.
    use VBOCronTrackerUnused;

    /**
     * This method should return all the form fields required to collect
     * the settings needed for the execution of the cron job.
     * 
     * @return  array  An associative array of form fields.
     */
    public function getForm()
    {
        return [
            'cron_lbl' => [
                'type'  => 'custom',
                'label' => '',
                'html'  => '<h4>' . $this->getTitle() . '</h4>',
            ],
            'address' => [
                'type'    => 'text',
                'label'   => 'Email Address',
                'default' => '',
            ],
            'subject' => [
                'type'    => 'text',
                'label'   => 'Email Subject',
                'default' => 'Dummy email message',
            ],
            'body' => [
                'type'    => 'visual_html',
                'label'   => 'Email Message',
                'default' => $this->getDefaultTemplate(),
                'attributes' => [
                    'id'    => 'tpl_body',
                    'style' => 'width: 70%; height: 150px;',
                ],
                'editor_opts' => [
                    'modes' => [
                        'text',
                        'modal-visual',
                    ],
                ],
                'editor_btns' => [],
            ],
            'help' => [
                'type'  => 'custom',
                'label' => '',
                'html'  => '<p class="info">Hey, this is just an example.</p>',
            ],
        ];
    }

    /**
     * Returns the title of the cron job.
     * 
     * @return  string
     */
    public function getTitle()
    {
        return 'Sample Task - Custom Cron Job';
    }
    
    /**
     * Executes the cron job.
     * 
     * @return  boolean  True on success, false otherwise.
     */
    protected function execute()
    {
        // collect the settings for this Cron Job instance
        $email_recipient = $this->params->get('address', '');
        $email_subject   = $this->params->get('subject', 'Default subject');
        $email_message   = $this->params->get('body');

        if (!$email_recipient) {
            // append execution log
            $this->appendLog('eMail address is empty');

            return false;
        }

        // for manual executions of the Cron Job, messages can be sent to output
        $this->output('<p>Sending an email to ' . $email_recipient . '</p>');

        /**
         * Here you could query the database or perform any kind of task.
         * In this example we send an email message according to the settings specified.
         */

        // get the sender email address from the settings of Vik Booking
        $admin_sendermail = VikBooking::getSenderMail();

        // decorate the email object
        $mail_data = new VBOMailWrapper([
            'sender'      => [$admin_sendermail, $admin_sendermail],
            'recipient'   => $email_recipient,
            'subject'     => $email_subject,
            'content'     => $email_message,
        ]);

        // dispatch the email sending command
        $result = VBOFactory::getPlatform()->getMailer()->send($mail_data);

        if ($result) {
            // log the successful event
            $this->appendLog('Message was sent correctly');
        }

        // return the result
        return $result;
    }

    /**
     * Returns the default e-mail message.
     * 
     * @return  string
     */
    protected function getDefaultTemplate()
    {
        static $tmpl = '';

        if (!$tmpl)
        {
            $sitelogo     = VBOFactory::getConfig()->get('sitelogo');
            $company_name = VikBooking::getFrontTitle();

            if ($sitelogo && is_file(VBO_ADMIN_PATH . DIRECTORY_SEPARATOR . 'resources'. DIRECTORY_SEPARATOR . $sitelogo))
            {
                $tmpl .= '<p style="text-align: center;">'
                    . '<img src="' . VBO_ADMIN_URI . 'resources/' . $sitelogo . '" alt="' . htmlspecialchars($company_name) . '" /></p>'
                    . "\n";
            }

            $tmpl .= 
<<<HTML
<h1 style="text-align: center;">
    <span style="font-family: verdana;">$company_name</span>
</h1>
<hr class="vbo-editor-hl-mailwrapper">
<h4>Dear Vik Booking User,</h4>
<p><br></p>
<p>This is an automated message to inform you that we are building a custom Cron Job.</p>
<p>You can always drop your luggage at the Hotel, should you arrive earlier.</p>
<p><br></p>
<p><br></p>
<p>Thank you.</p>
<p>$company_name</p>
<hr class="vbo-editor-hl-mailwrapper">
<p><br></p>
HTML
            ;
        }

        return $tmpl;
    }
}

That's all. You can package your plugin into a zip file that contains the main WordPress plugin file "custom-cron-jobs.php" and the folder "crons" that contains the actual Cron Job file just provided in the code example above ("sample_task.php"). Your plugin is ready to be installed onto your WordPress website, and then you can proceed with the setup of your custom Cron Job(s) through Vik Booking.

Last Update: 2024-01-30
Helpful?
67% of people found this helpful.