How to trigger WP-Cron from crontab in WordPress

By , last updated August 15, 2019

WordPress cron is a process that runs each time a user visits a website. It triggers the tasks that are due to run and schedules the new ones. Wp-cron is an important feature to have. It publishes posts that are scheduled to be published at given times. It triggers important background events like check for updates, send planned emails and others.

There is only one problem with WP-Cron – it is not a real cron. It runs only when someone visits your website. If no one visits – no cron jobs are executed. For example, if you plan your posts for several months ahead and set them to be automatically published each day at 8 o’clock in the morning – they won’t be publishes unless someone visits your website. No visitors – no cron jobs.

Popular websites with many visitors can run into another problem – cron checks and executes too many times and eats up all the resources. Many websites have problems when an unexpectedly large amount of visitors come. This will be worth if you have a regular wp-cron running.

The solution for WordPress cron default execution on page load is to disable it and trigger at regular intervals. Usually, ones every 6 hours is more than enough. If you auto publish your posts with WordPress schedule and need them to be published at once – trigger cron jobs at these timestamps as well.

Here is a step by step guide on how to fix WP-cron with Linux:

  1. Disable WP-Cron

    Open wp-config.php in an editor of your choice like Notepad or vim and add this. This will disable WP-Cron for everything, except when this script is called from the command line.

    if (php_sapi_name() !== 'cli')
        define('DISABLE_WP_CRON', true);
  2. Make cron script

    Create a new PHP file on a Linux server. We called it wpcron.php. We assume this script is one level up from the WordPress root, and that folder is called htdocs. Write the following code that will trigger WordPress cron:

    /** Setup WordPress environment **/
    /** Call to Run wp-cron **/
  3. Setup a real cron

    Edit cron to call the new PHP script wpcron.php and add this line to run the cron job every hour. The usual command to open up cron is crontab -e, and for viewing the cron is crontab -l.

    0 * * * * /usr/bin/php -f ~/webroot/wpcron.php

    For jobs every 6 hours, use this.

    0 */6 * * * /usr/bin/php -f ~/webroot/wpcron.php
  4. Test script

    Test with env -. If all is well, cron should run at scheduled times. Testing with env - is necessary to simulate the environment the cron is running under (as in no environment).

    env - /usr/bin/php -f ~/webroot/wpcron.php

    This line can also be used to trigger cron jobs manually if you need it.

Remember, if you run your cron jobs seldom, you may account a problem where your scheduled WordPress posts are not published. In this case make it run more often.