【发布时间】:2019-08-22 17:14:04
【问题描述】:
我已经构建了一个轮询 api 的 Wordpress 插件,该 api 与其他数据一起返回图像的 URL(轮询 api 的用户拥有这些图像)。将图像从 api 服务器移动到我的服务器非常耗时,但需要完成,因为我们希望 Wordpress 创建多种尺寸的图像 - 因此我们需要利用它的上传功能。有时数据可能会返回 500 多个结果,每个结果可能会返回多个图像。
我想将图像检索偏移到日常 CRON 工作中,但是我似乎无法让 cron 运行,我在代码中完成了以下操作,
wp-config.php
define('DISABLE_WP_CRON', true);
我像这样在我的插件代码中注册一个预定事件,
wp_schedule_event( time(), 'daily', 'process_images_hourly' );
这理论上应该把这个函数(下)放到一个工作列表中。
function process_images_hourly()
{
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM wp_autotrader_image_process WHERE process_status = 'Unprocessed';");
$processed_id = [];
foreach($results as $result) {
if(isset($result->image_url)) {
$upload_dir = wp_upload_dir();
$attachment_array = [];
if( !class_exists( 'WP_Http' ) ) {
include_once( ABSPATH . WPINC . '/class-http.php' );
}
$http = new WP_Http();
$file = file_get_contents($result->image_url);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$ext = $finfo->buffer($file);
if(strpos($ext, 'jpeg') || strpos($ext, 'jpg')) {
$type = '.jpg';
} elseif(strpos($ext, 'png')) {
$type = '.png';
} elseif(strpos($ext, 'gif')) {
$type = '.gif';
}
$response = $http->request( $result->image_url );
//die(print_r($image['secure']['href']));
if( $response['response']['code'] != 200 ) {
die(print_r($response['response']));
return false;
}
$upload = wp_upload_bits( basename($result->image_url), null, $response['body'] );
if( !empty( $upload['error'] ) ) {
die(print_r($upload));
return false;
}
$file_path = $upload['file'];
$file_name = basename( $file_path );
$file_type = wp_check_filetype( $file_name );
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
$wp_upload_dir = wp_upload_dir();
$post_info = array(
'guid' => $wp_upload_dir['url'] . '/' . $file_name . $type,
'post_mime_type' => $finfo->buffer($file),
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment( $post_info, $file_path );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
$attachment_array[] = $attach_id;
update_field( 'gallery', $attachment_array , $result->post_id );
$wpdb->delete( 'wp_autotrader_image_process', array( 'id' => $result->id ));
}
}
}
然后我的服务器上有 cronjob 来执行此操作,
*/15 * * * * curl https://Xxxxxx.xxxxxxxxx.com/wp-cron.php > /dev/null 2>&1 >/dev/null 2>&1
这会每十五分钟运行一次 wp-cron 文件。
但是我不认为我的函数正在运行,谁能解释为什么,或者如何正确设置它?
谢谢
【问题讨论】: