• I m working to randomize all the posts every day (as the date changes) by itself, and I have created a function that shuffles and returns the random post ids which I can use to show random posts.
    Anyways, all I want is to schedule this function to execute everyday at 12:00.
    I used WordPress function wp_schedule_event(); however that doesn’t seem to work. Has anyone worked on it before ? and know how to make it work? This is a test code I have used, m I doing something wrong?

    add_filter('cron_schedules', 'my_additional_schedules');
    function my_additional_schedules($schedules) {
        // interval in seconds just to test if it is working
        $schedules['every2min'] = array('interval' => 2*60, 'display' => 'Every two minutes');
        return $schedules;
    }
    
    // schedules the wp_cron_testing
    if( !wp_next_scheduled( 'wp_cron_testing' ) ) {
       wp_schedule_event( time(), 'every2min', 'wp_cron_testing' );
    }
    
    add_action( 'wp_cron_testing', 'the_wp_cron_test' );
    
    function the_wp_cron_test() {
        echo  "Here I have my code that needs to execute.";
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    Is this on a live site or a test site? Events will not fire unless some random request is made. On live sites, search bots usually generate enough traffic for this to work even if no one is reading your blog.

    Also, a event needs to perform some task, a simple echo has no where to go and will pass unoticed. For testing, try error_log('Here I have my code that needs to execute.'); so there is some evidence left that something happened.

    Thread Starter Mohammad Taqui Sayed

    (@sayedwp)

    Thanks for the reply, its not test site, but I didn’t want to show the whole complex code, its not echoing this text, it was only for illustration.
    Actually the function is getting random post ids from WP_Query, and I m saving it into the database with update_option( ‘home_mustview’, $random_post_ids ); The function does its job very well when I manually execute it.
    All the articles I read only suggest that I should disable WordPress Cron by define(‘DISABLE_WP_CRON’, true); and then use cron job from Cpanel or via ssh command. But why not get this function work and let it execute when a new visitor comes on the site.

    Moderator bcworkz

    (@bcworkz)

    Well, if you disable it it will not run on it’s own, you have to add wp-cron.php to crontab to have tasks run. This essentially simulates a site visit. People with heavily trafficked sites do it this way to cut down on server load because it’s stupid to check for tasks on every page load in such conditions.

    On low traffic sites it’s not a big deal to leave it enabled and not bother with crontab.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How to get wordpress cron job function working?’ is closed to new replies.