1

How can I run a WP function on server cron?

Background: I can't run it on wp_cron because the website is not published and will not be, so there will be no visitors. Tested cron job without wp function, it is working properly (like sending email every 30 minutes).

//RemoteCoins() and LoadRemoteCoins() that include wp functions like wp_remote_get()

function runthe_func() {

//some code here

}

runthe_func();

I kept on getting errors like: "Fatal error: Call to undefined function wp_remote_get() in /home/path/path2/testing.php on line 91"

How can I make it run with the server recognizing wp functions?

3
  • Welcome to WPSE. Short answer: You need to include wp-load.php in order to let your custom function recognize WP functions. – Pothi Kalimuthu May 17 '19 at 3:54
  • 1
    @PothiKalimuthu, thank you. It was the answer to my question. – kriskross May 17 '19 at 6:30
  • That's nice to know. Just put my short answer as a real answer to this question. – Pothi Kalimuthu May 17 '19 at 9:02
1

We need to include wp-load.php in order to bootstrap WordPress in our custom PHP code. So, the modified code would look something like this...

include '/path/to/wp-load.php';
//RemoteCoins() and LoadRemoteCoins() that include wp functions like wp_remote_get()

function runthe_func() {

//some code here

}

runthe_func();

Now, if we run this file on server cron, it wouldn't throw errors.

Oh, btw, similar questions have been asked and answered multiple times here in WPSE. For example, How to load WordPress on non WP page? .

1

@kriskross Welcome to the Community.

First of all, you need to create a scheduled event for WordPress cron jobs. You need to stay in functions.php (placed on your themes) or related files (plugin files etc.) for calling WordPress core functions. Also, you can create cron jobs from server side.

if you want to schedule please read and follow these instructions.

Create Server Handled Cron Jobs

place this configuration in your wp-config.php file before That's all, stop editing! Happy blogging.

define('DISABLE_WP_CRON', true);

after that, You need to create cron jobs from you local server (You said my website will not be released or get any visitors).

Here is the web based cron trigger link.

wget -q -O - http://yourdomain.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1

You can use online crontab generator like websites for timing and crontab.

I hope this will be your solution.

1
  • Since the site isn't published yet you may also consider running the cron using WP-CLI like so: 15 * * * * cd /var/www/mysite && /usr/bin/wp cron event run --due-now > /dev/null 2>&1 (runs every full hour + 15 minutes). – leymannx May 17 '19 at 9:24

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.