Я пытаюсь создать функцию WordPress, которая принимает URL-адрес изображения, загружает изображение, загружает его в медиатеку и возвращает идентификатор изображения.
Я адаптировал его из этого ответа, взятого отсюда, и добавил 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;
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/527 ... ia-library
Загрузите изображение по URL-адресу и загрузите в медиатеку WordPress. ⇐ Php
Кемеровские программисты php общаются здесь
1716440568
Anonymous
Я пытаюсь создать функцию WordPress, которая принимает URL-адрес изображения, загружает изображение, загружает его в медиатеку и возвращает идентификатор изображения.
Я адаптировал его из этого ответа, взятого отсюда, и добавил 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;
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/52789439/download-image-from-url-and-upload-to-wordpress-media-library[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия