Issue with wp_schedule_event()

I am trying to set up an event on a custom interval that will grab new posts from an Instagram search and create them as wordpress posts. I had the code working on its own page, and now I am trying to schedule it to happen automatically.

I have also installed Wp Crontroller to ensure the event is being recognized by WordPress (which it is) but I cannot seem to get the code to run (nor can I figure out how to debug it.

Read More
add_action( 'wp', 'create_schedule' );

function create_schedule() {
  wp_schedule_event(time(), 'quarter_hour', 'ig_fetch_start');
  update_option('test', 'Close!');
}

add_action('ig_fetch_start','ig_fetch_new_posts');

function ig_fetch_new_posts() {
  update_option('test', 'Fired');
  // Run function
}

The option update is in there just to see if the event is firing. WordPress simple never seems to make it to the ig_fetch_new_posts function.

Related posts

Leave a Reply

1 comment

  1. You need to schedule the event differently. In your approach, you hook to wp to schedule the event, meaning that it is called everytime WordPress is called, setting your option back.

    I am not quite sure if the schedule is postponed or if you create multiple schedules this way, but it is not correct.

    You should check if this event is scheduled (using wp_next_scheduled()), and only schedule if this function returns false, to avoid multiple entries/postponing issues.

    I would also use two different options to check if the functions get called, because due to the architecture of this system, as soon as your scheduled function is fired, the value changes – only to be overwritten when you next call WordPress, as no event is scheduled.

    I also added a time to the optionvalue, to check when it was registered. I always like to know stuff like that on debugging.

    The script (including the registration of a new schedule) would look something like this:

    add_filter( 'cron_schedules', 'f711_add_quarter_hour_cron_schedule' );
    function f711_add_quarter_hour_cron_schedule( $schedules ) {
        $schedules['quarter_hour'] = array(
            'interval' => 900, // Time in seconds
            'display'  => __( 'Quarter Hour' ),
        );
    
        return $schedules;
    }
    
    if ( ! wp_next_scheduled( 'ig_fetch_new_posts_hook' ) ) { // check if function is scheduled
        wp_schedule_event( time(), 'quarter_hour', 'ig_fetch_new_posts_hook' ); // if not, schedule it
        update_option('test_scheduled', 'scheduled' . time() ); // set your scheduleoption to scheduled
    }
    
    add_action( 'ig_fetch_new_posts_hook', 'ig_fetch_new_posts' ); // define the hook for the schedule
    
    function ig_fetch_new_posts() { // your updatemagic
        update_option('test_fired', 'Fired' . time() );
        // Run function
    }