0

I am working on a wordpress website. I want to do some updates on the products via a cpanel cron job. for that I created a new file at the root /public_html/update-products.php and on cpanel added the cron job command:

/usr/local/bin/php /home1/blahblah/public_html/update-products.php

my problem is that I want to use wordpress functions in this file like get_option, update_option, update_post_meta ... etc

what file from wordpress should I include at the top of my file. I tried to include the index.php file itself so I can use such functions.

here is the file code (update-products.php)

require_once __DIR__ . '/index.php';

require_once __DIR__ . '/wp-content/plugins/citycenter-products/includes/api.php';

$last_update_info = get_option(DS_CITYCENTER_PRODUCTS_LAST_UPDATE_COMPACT_OPTION);

$data = array('type' => 'compact');
if ($last_update_info) {
    $data['from_datetime'] = $last_update_info['date'].' '.$last_update_info['time'];
}

$result = update_citycenter_products($data);

$last_update_info = array(
    'type' => 'compact',
    'date' => date('Y-m-d'),
    'time' => date('H:i:s'),
    'total' => $result['total'],
    'updated' => $result['updated'],
    'added' => $result['added'],
);
update_option(DS_CITYCENTER_PRODUCTS_LAST_UPDATE_COMPACT_OPTION, $last_update_info);
anwar
  • 103
  • 1
  • 10

2 Answers2

0

This is because your file is outside of WordPress, so in the end a standalone PHP script.

Take a look at Wordpress documentation about the CRON job. WordPress has its own way of handling CronJob properly. Following this method, you'll have access to all the WordPress ecosystem (methods and stuff).

If you really want to load the WordPress ecosystem in your standalone script, it's the wp-load.php file that is needed. Check this stack.

Mtxz
  • 3,749
  • 15
  • 29
  • the problem with wordpress cron jobs is that a page load is needed to run. I don't want to wait for a visitor to load some page – anwar Jul 03 '21 at 15:51
  • No, you can also use a classic CRON HTTP call to a specific WP URL to trigger the Cron. The "on user visit" method is another option (https://www.​example.com/wp-cron.php?doing_wp_cron) - doing this you can disable the on user visite option. – Mtxz Jul 03 '21 at 15:52
  • But I think this will run all cron jobs registered not only mine – anwar Jul 03 '21 at 15:58
  • Yes it will "trigger if needed" them, based on the CROn delay setup for each job. But its the best way to handle WordPress CRON jobs, and adding yours to it. Anyway, you can also load WP core as I linked – Mtxz Jul 03 '21 at 17:40
0

Replace with require_once __DIR__ . '/wp-load.php'; instead of require_once __DIR__ . '/index.php';