- Programmatically adding images to media library
- 3 Answers 3
- WordPress Загрузить медиа для публикации
- 8 ответов
- Uploading of image to WordPress through Python’s requests
- BrainyCP
- Решение 500 Internal Server Error на WordPress
- Решение 500 Internal Server Error на WordPress
- Upload file which contain no extension into wordpress?
- 5 Answers 5
Programmatically adding images to media library
I am trying to programmatically add multiple images to media library, I uploaded the images to wp-content/uploads , now I try to use wp_insert_attachement . Here’s the code, however it’s not working as expected, I think metadata is not properly generated, I can see the files in media library, but without a thumbnail, also if I edit the image I get an error saying to re-upload the image.
$filename_array = array( 'article1.jpg', 'article2.jpg', ); // The ID of the post this attachment is for. $parent_post_id = 0; // Get the path to the upload directory. $wp_upload_dir = wp_upload_dir(); foreach ($filename_array as $filename) < // Check the type of file. We'll use this as the 'post_mime_type'. $filetype = wp_check_filetype( basename( $filename ), null ); // Prepare an array of post data for the attachment. $attachment = array( 'guid' =>$wp_upload_dir['url'] . '/' . basename( $filename ), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ), 'post_content' => '', 'post_status' => 'inherit' ); // Insert the attachment. $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id ); // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. require_once( ABSPATH . 'wp-admin/includes/image.php' ); // Generate the metadata for the attachment, and update the database record. $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); >
3 Answers 3
$image_url = 'adress img'; $upload_dir = wp_upload_dir(); $image_data = file_get_contents( $image_url ); $filename = basename( $image_url ); if ( wp_mkdir_p( $upload_dir['path'] ) ) < $file = $upload_dir['path'] . '/' . $filename; >else < $file = $upload_dir['basedir'] . '/' . $filename; >file_put_contents( $file, $image_data ); $wp_filetype = wp_check_filetype( $filename, null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name( $filename ), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $file ); require_once( ABSPATH . 'wp-admin/includes/image.php' ); $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); wp_update_attachment_metadata( $attach_id, $attach_data );
@UmairHamid Same here. This is because the second argument of wp_insert_attachment should be the file path (so $file in this example), not the file name. I edited the answer, waiting for approval.
WordPress Загрузить медиа для публикации
Дело в том, что я пробовал чистую установку в другой домен на том же сервере, он работает так, как должен.
В чем может быть проблема? Как я могу это исправить?
Можете ли вы проверить пользователей и группы владельцев дерева WordPress? Кроме того, вы получаете, что панель «загрузки» достигает 100%, а затем показывает ошибку? Ваши загруженные изображения получают все свои эскизы, созданные правильно? Проверьте wp-uploads и панель Media, чтобы увидеть, если они есть.
«Когда я пытаюсь добавить из wp-admin / media-new.php, используя multi-uploader, файл останавливается на шаге« Crunching… », но загрузка старого браузера работает безупречно.», Не могли бы вы рассказать, что происходит у вас » Вкладка «Сеть» для Firebug, инспектор, что бы вы ни делали?
@Alainus без ошибок вообще. Я уже проверил. Также группа и владельцы верны. Странно, когда я усекаю таблицу wp_posts, она загружается правильно. Но я не уверен, что является причиной этой ошибки.
8 ответов
Посмотрите, есть ли у пользовательского типа сообщений какие-либо файлы, находящиеся в UTF-8. Если вы измените его на ANSI, это должно помочь, если это проблема.
Не имеет прямого отношения к этому, но я столкнулся с такой же проблемой после того, как переместил тот же сайт на другой сервер. Единственное отличие — теперь я использую Nginx вместо Apache. Я проверял владельцы раньше, и все они были правильны (иначе обычная загрузка не будет работать и раньше). Я оставляю это здесь как ссылку.
Исправление в моем новом случае было простым изменением права собственности на веб-корень и все файлы внутри.
Nginx и PHP5-FPM работают с одним и тем же пользователем: www-data , который находится в группе с тем же именем: www-data .
Таким образом, изменение всех прав собственности на файлы, зафиксированные в этом случае:
su chown -R www-data:www-data /path/to/wordpress/root/
Я до сих пор не знаю первоначальной причины моей старой проблемы, мне пришлось вытирать, начинать с чистого листа и восстанавливать сообщения, плагины и т.д. с нуля.
Uploading of image to WordPress through Python’s requests
In order to validate the installation of WordPress instances, we are writing Python unit tests. One of the test should perform the following action: upload an image to WordPress. In order to do that, I am using the Requests library. When I inspect the form within /wp-admin/media-new.php page through Firebug (form information, I get the following information): Form Id: file-form Name Method: post Action: http://localhost:8000/wp-admin/media-new.php Elements id: plupload-browse-button type: button value: Select Files id:async-upload name: async-upload type: file label: Upload id:html-upload name: html-upload type: submit value: Upload id: post_id name: post_id type: hidden value: 0 id: _wpnonce name: _wpnonce type: hidden value: c0fc3b80bb id: file-form name: _wp_http_referer type: hidden value: /wp-admin/media-new.php I believe that the _wpnonce is a unique value generated for each session. Therefore, before trying to upload the file, I get the media-new.php page and grab the _wpnonce in the form (hence the variable in my code). My code is the following:
with open('1.jpg', 'rb') as f: upload_data = upload_result = session.post('http://localhost:8000/wp-admin/media-new.php', upload_data)
The code runs fine and the upload_result.status_code equals 200. However, the image never shows up in the media gallery of WordPress. I believe this a simple error, but I can’t figure out what I’m missing. Thanks in advance for the help.
BrainyCP
Решение 500 Internal Server Error на WordPress
Решение 500 Internal Server Error на WordPress
Сообщение nup0TexHuk » Вт фев 09, 2021 1:32 pm
Всем привет.
Хочу представить очередное решение проблемы, которое связано с настройками BrainнCP (что в Интернете не опубликовано / не найдено)
Ситуация следующая: при попытке загрузить любой файл (с разными расширениями и названиями) через родной загрузчик WP — Медиафайлы, возникала ошибка
«Всё ясно!» — скажите вы — «нет прав на запись или лимит по размеру файла»
А вот и нет! — если пробовать загрузить любой файл до 130Kb — загрузка проходит штатно и без ошибок.
Нагуглив все возможные варианты решения, пробовал следующее:
-менять папку для загрузки и права к ней (755, 777)
-проверял в брэйни upload_maxsize и всякие лимиты
-проверял/создавал новые .htaccess и php.ini (с указанием лимитов)
-отключал полностью все плагины и менял тему (!) обычно помогает в 60% случаев различных ошибок в WP
-даже качал свежий wordpress и заменял папки wp-admin и wp-includes
-включал wp_debug и debug_log, но там ничего
-пытался дописать SecUploadDir и SecTmpDir в user.conf
(в общем всё, что нашел на русско- и англо-язычных форумах)
Но ничего из вышеперечисленного не помогло.
Также в логах сайта (/etc/httpd/vhost_logs/domain_error и/или /etc/nginx/vhost_logs/domain_error) обнаружил следующую запись:
И да, забыл отметить — всё это касалось только одного из сайтов на вордпрессе. А их у меня на хосте — больше 5. И нигде в других данная проблема не наблюдалась.
В итоге, решение нашлось по адресу в Brainy CP: Вэбсервер > Дополнительная настройка сайтов > (выбираем юзера и домен) — Параметры apache для сайта домен.ru
Перед закрывающим тегом у меня отсутствовали 3 строчки:
Upload file which contain no extension into wordpress?
The statement was written into wp-includes/functions.php .
Edit a simple file named test which contain no any extension.
vim test to upload the file which contain no file extension.
This file type is not allowed. Please try another.
add_filter('upload_mimes','custom_upload_mimes'); function custom_upload_mimes ( $existing_mimes=array() ) < $existing_mimes['txt'] = 'application/txt'; return $existing_mimes; >
The file test.txt can be uploaded successfully.
It is no use to set in the configure file wp-config.php .
define('ALLOW_UNFILTERED_UPLOADS', true);
I am using a child of twentyfourteen. Here is my /var/www/html//wp-content/themes/twentyfourteen-child/functions.php
get('Version') ); > add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); remove_filter('the_content', 'wptexturize'); remove_filter('the_excerpt', 'wptexturize'); remove_filter('comment_text', 'wptexturize'); ?>
WordPress does not output a error like «This file type is not allowed», i searched for this string exactly, nothing to be found, are you uploading via your media library? Maybe it’s an error message outputted by your server instead? But I can’t tell for sure, but at least couldn’t find that string, that’s for sure (latest WP version).
5 Answers 5
The real problem is not with WordPress’s backend but it’s frontend validation. The uploader is handled by Plupload and by default, WordPress is only checking if you have defined ALLOW_UNFILTERED_UPLOADS in the uploading progress, without really tweaking the frontend plugin’s filter validation with the value. Perhaps a small frontend glitch.
As you can see, WordPress is always rendering the following default settings:
var _wpPluploadSettings = ]>,"multipart_params":>,"browser":,"limitExceeded":false>;
A temporary fix to the problem before they fix it on their end would be hooking in the filters WordPress is calling to generate the frontend settings, plupload_default_settings .
Add the filter in your functions.php :
add_filter('plupload_default_settings', function ($settings) < if (defined('ALLOW_UNFILTERED_UPLOADS') && ALLOW_UNFILTERED_UPLOADS) < unset($settings['filters']['mime_types']); >return $settings; >);
This will allow you to upload your test via the uploader. Since WordPress is checking already in the backend, as long as you have defined it in your wp-config.php that ALLOW_UNFILTERED_UPLOADS is true , it should be uploaded properly.