【发布时间】:2018-10-13 04:08:43
【问题描述】:
我正在尝试构建一个 WordPress 函数,该函数获取图像 URL、下载图像、将其上传到媒体库并返回图像 ID。
我从this answer 改编而来,原来是taken from here,最后添加了wp_insert_attachment()。
目前它不起作用,因为它不返回任何内容或上传任何媒体。
通过var_dump() 逐步调试,我发现$url 参数被正确传递,但download_url 没有任何输出。
你知道哪里错了吗?
你能在函数中看到其他可能被破坏的东西吗?
/* Add image to media library from URL and return the new image ID */
function bg_image_upload($url) {
// Gives us access to the download_url() and wp_handle_sideload() functions
require_once( ABSPATH . 'wp-admin/includes/file.php' );
// Download file to temp dir
$timeout_seconds = 10;
$temp_file = download_url( $url, $timeout_seconds );
if ( !is_wp_error( $temp_file ) ) {
// Array based on $_FILE as seen in PHP file uploads
$file = array(
'name' => basename($url), // ex: wp-header-logo.png
'type' => 'image/png',
'tmp_name' => $temp_file,
'error' => 0,
'size' => filesize($temp_file),
);
$overrides = array(
// Tells WordPress to not look for the POST form
// fields that would normally be present as
// we downloaded the file from a remote server, so there
// will be no form fields
// Default is true
'test_form' => false,
// Setting this to false lets WordPress allow empty files, not recommended
// Default is true
'test_size' => true,
);
// Move the temporary file into the uploads directory
$results = wp_handle_sideload( $file, $overrides );
if ( !empty( $results['error'] ) ) {
// Insert any error handling here
} else {
$filename = $results['file']; // Full path to the file
$local_url = $results['url']; // URL to the file in the uploads dir
$type = $results['type']; // MIME type of the file
$wp_upload_dir = wp_upload_dir(); // Get the path to the upload directory.
$attachment = array (
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_mime_type' => $type,
'post_status' => 'inherit',
'post_content' => '',
);
$img_id = wp_insert_attachment( $attachment, $filename );
return $img_id;
}
}
}
【问题讨论】:
-
您检查过网络服务器日志吗?您可能需要在 PHP 上启用调试,看看是否能给您一些提示。
-
@sal 刚刚检查了错误日志,但它们是空的
-
检查您的网络服务器日志。 /var/logs/nginx/error_log 例如 nginx。
-
出现错误!我只是之前没有打开它。它显示
PHP Fatal error: Uncaught Error: Call to undefined function wp_generate_password(),但我不知道为什么,因为我从来没有打电话。这是完整的错误文本:pastebin.com/kf68j5YE -
首先想到的可能是该功能在 WP:check this article 中没有正确连接。抱歉,虽然我了解 WP,但它不是我的面包和黄油。希望这无论如何都会有所帮助:-)