1
  • I have cron jobs successfully working in WordPress,
  • However, when I attempt to call a class from within the cron function it doesn't run.
  • How would I call in a class with a cron job function?

add_action( 'hourly_event', 'hourly_function' );
function hourly_function() {
   // This otherwise works when not within a cron job function
   $newClass = new newClass();
   $newClass->newClass_function($var1, $var2, $var3); 
}

$newClass is declared within plugin.


require plugin_ROOT.'gd-text/Box.php';
require plugin_ROOT.'gd-text/Color.php';
require plugin_ROOT.'gd-text/HorizontalAlignment.php';
require plugin_ROOT.'gd-text/TextWrapping.php';
require plugin_ROOT.'gd-text/VerticalAlignment.php';

use GDText\Box;
use GDText\Color;


class newClass {

    public function newClass_function($var1, $var2, $var3){
    }
}
  • Is the log showing an error for that call? Also, and it may be a typo here, but you are missing the parans on your class instantiation. It should be $newClass = new newClass(); – jdm2112 Nov 14 '16 at 18:49
  • Yes, just a typo. And no error gets shown in php log. – Jimmy PHP Nov 14 '16 at 21:08
  • How to do you declare newClass class and where? – Samuel Elh Nov 14 '16 at 21:17
  • It is declared in a plugin. See edited answer for specific code. – Jimmy PHP Nov 14 '16 at 21:30
  • What is the hourly_event action? I don't believe that is a standard Wordpress hook. And for a Wordpress cron to work you need to have someone or something hitting your site to trigger it. – ngearing Nov 14 '16 at 22:27
1

You're calling a function with variables that are not defined and are required for the function to work correctly.

function hourly_function() {

   $newClass = new newClass();

   $var1 = 'this should';
   $var2 = 'work with';
   $var3 = 'some content';

   $newClass->newClass_function($var1, $var2, $var3); 
}

You might want to move those variable to a __construct

if ( ! class_exists('AClass')) {
    class AClass {
        function __construct( $var1 = null, $var2 = null, $var3 = null ) {
            //...
        }
    }
}
$instance = new AClass(1,2,3);

Or the __invoke method:

if ( ! class_exists('BClass')) {
    class BClass {
        function __invoke( $var1 = null, $var2 = null, $var3 = null ) {
            //...
        }
    }
}
$instance = new BClass();
$instance(1,2,3);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.