mrz_zahmatkesh
mrz_zahmatkesh

Reputation: 51

How to add a cron job to a WordPress page?

How to add a cron job to a WordPress page?

I tried adding this code:

<?php

add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
function isa_add_every_three_minutes( $schedules ) {
    $schedules['every_three_minutes'] = array(
        'interval'  => 180,
        'display'   => __( 'Every 3 Minutes', 'textdomain' )
    );
    return $schedules;
}

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'isa_add_every_three_minutes' ) ) {
    wp_schedule_event( time(), 'every_three_minutes', 'isa_add_every_three_minutes' );
}

// Hook into that action that'll fire every three minutes
add_action( 'isa_add_every_three_minutes', 'every_three_minutes_event_func' );
function every_three_minutes_event_func() {
    // do something

    echo "red";
}
?>

into page-price.php

It should be printed every 3 minutes.

But this doesn't work.

Upvotes: 0

Views: 229

Answers (1)

ahendwh2
ahendwh2

Reputation: 382

A cron job cannot be applied to a page. A cron job is some code which only affects the server side. Furthermore WordPress doesn't have real cron jobs by default. In WordPress the cron job tasks are triggered, if someone visits your website and the interval has passed, but the cron job execution is indepentend from the site visit (see part "Description" of wp_schedule_event()). Normally cron jobs would be triggered by the operating system of your server.

If you want something to be done on a page, you have to use a javascript based solution (see setInterval()). In the javascript function you can use ajax, if you need to execute server-side code and get information from your server.

Upvotes: 1

Related Questions