【发布时间】:2018-04-09 04:41:53
【问题描述】:
尝试在 Cpanel 上添加一个 cron 作业以每 5 分钟运行一次。我将此添加到命令输入中(从 url 中删除了个人详细信息)
/usr/bin/php -q /home/my_name/public_html/staging/the_web_site/wp-content/themes/my_child_theme/functions.php updateproducts
然后在functions.php,我有这个:
if (!empty($argv[1])) {
switch ($argv[1]) {
case "updateproducts":
update_products();
break;
}
}
如果我使用管理页面上的按钮触发update_products() 函数,则手动运行它时不会出现任何错误。但是,无论我在 cronjob 选项卡上做什么,它都不会运行。
有什么想法吗?
function update_products() {
global $wpdb;
$groups = get_groups_from_cron_jobs(100);
foreach ( $groups as $group ) {
$name = $group->group_name;
$sql = $wpdb->prepare("SELECT * FROM {$wpdb->prefix}products WHERE name='%s'", $name);
$products = $wpdb->get_results($sql);
if ( !empty($products) ){
$post_id = get_post_id_from_products($products);
//if there isn't a parent_id then create a new product
if ( !$post_id && $name != '' ) {
$post_id = create_a_new_product($name);
}
// make sure that all products will have now a parent_id
add_parent_id_on_products($name, $post_id);
insert_product_attributes($post_id, $products);
insert_product_variations($post_id, $products);
delete_group_from_cron_jobs($name);
}
}
}
编辑:根据答案/cmets,我进行了额外的研究,发现我可以在任何脚本上加载 $wpdb。我做的是这样的:
if (!empty($argv[1])) {
switch ($argv[1]) {
case "updateproducts":
$path = $_SERVER['DOCUMENT_ROOT'];
require( $path . '/staging/the_web_site/wp-load.php' );
update_products();
break;
}
}
但是,我仍然在电子邮件中收到错误:
Status: 500 Internal Server Error
X-Powered-By: PHP/5.6.31
Content-type: text/html; charset=UTF-8
【问题讨论】:
-
您确定它根本没有运行吗?您能否检查您的服务器日志以查看 cron 作业是否产生了任何错误?
-
我添加了一封电子邮件以接收输出并删除了 -quite 模式。我得到一个
Status: 500 Internal Server Error。这很奇怪,因为我可以手动运行它 -
你能发布你的
update_products函数吗? -
@CGriffin 完成。但正如我所说,如果我在表单上的单击事件中添加该函数,它会运行并且我会得到想要的结果