0

I'm building a plugin that tracks the time a user spends at a specific page. I want a plugin thats updates every second to the database, but maybe this isn't the best way. But with this code, it updates only once. Why is that? I hope you can help me!

function add_new_intervals( $schedules ) {
    // Adds once every second to the existing schedules.
    $schedules['1sec'] = array(
        'interval' => 1,
        'display' => __( 'Once every second' )
    );
    return $schedules;
 }

// Add new schedule time
add_filter( 'cron_schedules', 'add_new_intervals' );


register_activation_hook(__FILE__, 'my_activation');

function my_activation() {
    wp_schedule_event(time(), '1sec', 'my_event');
}


add_action('my_event', 'do_this_every_second');

$counter = 0;

function do_this_every_second() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'myplugin';
    $wpdb->update( 
        $table_name, 
        // Set data
        array( 'visit_time' => $counter),
        // Where
        array('id' => 1) //just for testing
    );
    $counter += 1;
}


register_deactivation_hook(__FILE__, 'my_deactivation');
function my_deactivation() {
    wp_clear_scheduled_hook('my_event');
}
  • Any reason you couldn't just use Google Analytics? It tracks all this info and there are plugins that will integrate it with the WP dashboard. – WebElaine Jun 13 '17 at 20:49
  • @WebElaine It's for a school project. We have to build it ourselves. – Hunter Jun 13 '17 at 21:19
  • WP Cron only runs when someone is actively using the website, so you may want to look into an actual server cron job rather than a WP one. – WebElaine Jun 13 '17 at 21:31
  • @WebElaine Is there a better way to track the users visited time for each page? – Hunter Jun 13 '17 at 21:49
  • 1
    a better can be that at every page call of the user you save the last time where it was connected. after you just have do calculate the difference between the first and the last time it was visiting a page – mmm Jun 13 '17 at 23:38

Your Answer

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

Browse other questions tagged or ask your own question.