最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Setup wp_schedule_event within a custom plugin

programmeradmin2浏览0评论

I am using WordPress 4.9.6 and I am trying to create a plugin that pulls data from an external API.

See below my current code:

myPlugin.php

<?php
/**
Plugin Name: myPlugin
description: Get Data via APIs
Version: 1.0
Author: Batman
License: GPLv2 or later
Text Domain: myPlugin
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

require_once 'vendor/autoload.php';

class My_Plugin {

      /**
     * Constructor.
     */
    public function __construct() {
        define( 'MyPlugin_FILE', __FILE__ );
        define( 'MyPlugin_DIR', trailingslashit( dirname( __FILE__ ) ) );
        define( 'MyPlugin_VERSION', '0.0.1' );
        register_activation_hook( basename( MyPlugin_DIR ) . '/' . basename( MyPlugin_FILE ), array( $this, 'activate' ) );
        add_action( 'plugins_loaded', array( $this, 'includes' ) );
        add_action( 'init', array( $this, 'maybe_update' ) );
    }

    public function activate() {
        $this->includes();
        flush_rewrite_rules();
    }

    public function includes() {
        include_once( MyPlugin_DIR . 'includes/WhatToMineAPI.php' );
    }

    /**
     * Maybe update MyPlugin.
     */
    public function maybe_update() {
        $version = get_option( 'MyPlugin_version', 0 );
        if ( version_compare( $version, MyPlugin_VERSION, '<' ) ) {
            $this->create_tables();
            update_option( 'MyPlugin_version', MyPlugin_VERSION );
        }
    }
}
new My_Plugin();

WhatToMineAPI.php

<?php

use GuzzleHttp\Client;

class WhatToMineAPI {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action( 'setupCronJob_whatToMine', 'setupCronJob');
        add_action( 'update_whatToMine_api', 'updateWhatToMineAPI');

        // variables
        $whatToMineURL = ".json";
    }

    public function setupCronJob() {
        //Use wp_next_scheduled to check if the event is already scheduled
        $timestamp = wp_next_scheduled( 'update_whatToMine_api' );

        //If $timestamp == false schedule daily backups since it hasn't been done previously
        if( $timestamp == false ){
            //Schedule the event for right now, then to repeat daily using the hook 'update_whatToMine_api'
            wp_schedule_event( time(), 'twicedaily', 'update_whatToMine_api' );
        }
    }

    public function updateWhatToMineAPI() {

        $client = new GuzzleHttp\Client();

        $response = $client->request('GET', $whatToMineURL);

    }


}
new WhatToMineAPI();

I have installed the plugin WP-Control to get an overview of my running cron-jobs. However, my cron-job update_whatToMine_api cannot be found within the table?

Is my current cron-setup wrongly done?

I appreciate your replies!

I am using WordPress 4.9.6 and I am trying to create a plugin that pulls data from an external API.

See below my current code:

myPlugin.php

<?php
/**
Plugin Name: myPlugin
description: Get Data via APIs
Version: 1.0
Author: Batman
License: GPLv2 or later
Text Domain: myPlugin
*/

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

require_once 'vendor/autoload.php';

class My_Plugin {

      /**
     * Constructor.
     */
    public function __construct() {
        define( 'MyPlugin_FILE', __FILE__ );
        define( 'MyPlugin_DIR', trailingslashit( dirname( __FILE__ ) ) );
        define( 'MyPlugin_VERSION', '0.0.1' );
        register_activation_hook( basename( MyPlugin_DIR ) . '/' . basename( MyPlugin_FILE ), array( $this, 'activate' ) );
        add_action( 'plugins_loaded', array( $this, 'includes' ) );
        add_action( 'init', array( $this, 'maybe_update' ) );
    }

    public function activate() {
        $this->includes();
        flush_rewrite_rules();
    }

    public function includes() {
        include_once( MyPlugin_DIR . 'includes/WhatToMineAPI.php' );
    }

    /**
     * Maybe update MyPlugin.
     */
    public function maybe_update() {
        $version = get_option( 'MyPlugin_version', 0 );
        if ( version_compare( $version, MyPlugin_VERSION, '<' ) ) {
            $this->create_tables();
            update_option( 'MyPlugin_version', MyPlugin_VERSION );
        }
    }
}
new My_Plugin();

WhatToMineAPI.php

<?php

use GuzzleHttp\Client;

class WhatToMineAPI {

    /**
     * Constructor.
     */
    public function __construct() {
        add_action( 'setupCronJob_whatToMine', 'setupCronJob');
        add_action( 'update_whatToMine_api', 'updateWhatToMineAPI');

        // variables
        $whatToMineURL = "http://whattomine.com/coins.json";
    }

    public function setupCronJob() {
        //Use wp_next_scheduled to check if the event is already scheduled
        $timestamp = wp_next_scheduled( 'update_whatToMine_api' );

        //If $timestamp == false schedule daily backups since it hasn't been done previously
        if( $timestamp == false ){
            //Schedule the event for right now, then to repeat daily using the hook 'update_whatToMine_api'
            wp_schedule_event( time(), 'twicedaily', 'update_whatToMine_api' );
        }
    }

    public function updateWhatToMineAPI() {

        $client = new GuzzleHttp\Client();

        $response = $client->request('GET', $whatToMineURL);

    }


}
new WhatToMineAPI();

I have installed the plugin WP-Control to get an overview of my running cron-jobs. However, my cron-job update_whatToMine_api cannot be found within the table?

Is my current cron-setup wrongly done?

I appreciate your replies!

Share Improve this question asked May 26, 2018 at 12:13 Carol.KarCarol.Kar 3771 gold badge8 silver badges18 bronze badges 2
  • 1 Where are you calling setupCronJob()? – kero Commented May 26, 2018 at 14:16
  • @kero Basically, when I activate my plugin the cron-job should also get activated. I thought that add_action does this job for me. Any suggestions how to call setupCronJob, when activating the plugin? I appreciate your reply! – Carol.Kar Commented May 26, 2018 at 14:51
Add a comment  | 

1 Answer 1

Reset to default 4

First of all: if you haven't read it already, please check the official documentation on WP-Cron.

The problem in your code is this line

    add_action( 'setupCronJob_whatToMine', 'setupCronJob');

You're defining a new action setupCronJob_whatToMine and add the setupCronJob method to it. But as this is a custom action you just created, it will never be called (eg via do_action('setupCronJob_whatToMine');).

So instead of adding it to an action, you can call setupCronJob() directly to set up the event scheduling.

You can do it in the init action. However, this will add the logic to every page load, which is unnecessary. A cron like needs to be set up only once.

So I'd add the Cron in the activation hook (and don't forget to remove it in the deactivation hook).

Simple code example:

MyPlugin.php

register_activation_hook( __FILE__, array(My_Plugin::class, 'activate') );
register_deactivation_hook( __FILE__, array(My_Plugin::class, 'deactivate') );

class MyPlugin
{

    public static function activate()
    {
        WhatToMineAPI::setupCronJob();
    }

    public static function deactivate()
    {
        WhatToMineAPI::unsetCronJob();
    }

    // your other methods

}

WhatToMineAPI.php

class WhatToMineAPI
{

    const CRON_HOOK = 'update_whatToMine_api';

    public static function setupCronJob()
    {
        //Use wp_next_scheduled to check if the event is already scheduled
        $timestamp = wp_next_scheduled( self::CRON_HOOK );

        //If $timestamp === false schedule daily backups since it hasn't been done previously
        if( $timestamp === false ){
            //Schedule the event for right now, then to repeat daily using the hook 'update_whatToMine_api'
            wp_schedule_event( time(), 'twicedaily', self::CRON_HOOK );
        }
    }

    public static function unsetCronJob()
    {
        // Get the timestamp for the next event.
        $timestamp = wp_next_scheduled( self::CRON_HOOK );
        wp_unschedule_event( $timestamp, self::CRON_HOOK );
    }

    public function __construct()
    {
        add_action(self::CRON_HOOK, array($this, 'updateWhatToMineAPI'));
    }

    public function updateWhatToMineAPI()
    {
        $client = new GuzzleHttp\Client();
        $response = $client->request('GET', $whatToMineURL);
    }

}

Side note: When working with classes, you need to beware. Either use add_action('...', array($this, 'methodName')) but then you need $this or similar defined.

Alternatively you can use static methods like so add_action('...', array(MySuperClass::class, 'staticMethodName'))

发布评论

评论列表(0)

  1. 暂无评论