WordPress php image upload

How To Upload Images To The WordPress Media Library

This quick guide shows you how to set up a form to upload images to your media library using the free WordPress plugin Snippy.

Creating a File Upload Handler

First step, let’s open your themes functions.php file, and add the code snippet below. This will create a location for us to send our files to.

function handle_my_file_upload()  // will return the attachment id of the image in the media library $attachment_id = media_handle_upload('my_file_field', 0); // test if upload succeeded if (is_wp_error($attachment_id))  http_response_code(400); echo 'Failed to upload file.'; > else  http_response_code(200); echo $attachment_id; > // done! die(); > // allow uploads from users that are logged in add_action('wp_ajax_my_file_upload', 'handle_my_file_upload'); // allow uploads from guests add_action('wp_ajax_nopriv_my_file_upload', 'handle_my_file_upload');

There are a couple things to take note of:

  • handle_my_file_upload is the name of the function that will deal with the upload, both add_action calls reference it.
  • wp_ajax_ and wp_ajax_noprive_ are default hooks, we add my_file_upload to them to allow communication with our form which we’ll set up next.
  • Comment out the nopriv call to prevent file uploads from guests.

Creating the Form

Alright now we need to add a to give the user a location to select the images they want to upload.

We’ll use the free WordPress plugin Snippy to create a shortcode that we can use everywhere on our WordPress website.

With Snippy installed we’ll start by creating an HTML bit. Click on the “Snippy/Add Bit” menu item. Name your HTML bit “file-form”. Set type to “HTML”. And paste the code below in the textfield.

form action=">" method="POST" enctype="multipart/form-data" > input type="hidden" name="action" value="my_file_upload" /> label for="image">Select file:label> input type="file" id="image" name="my_file_field" accept="image/*" /> button type="submit">Uploadbutton> form>
  • my_file_upload corresponds to the value used in the add_action calls.
  • my_file_field corresponds to the value used in the media_handle_upload call.

Now we’ll create our custom shortcode.

Click “Snippy/Add Shortcode” and use “file-upload” as the name. In the “Available bits” list we select our “file-form”. Click Save.

That’s it! We now have a form shortcode at our disposal.

Add it to a page (using the page editor), refresh the page, your file upload form should now appear.

Bonus: Editing the Image

Let’s upgrade our form to allow our users to edit dropped images using Pintura

We can use Snippy to add the Pintura files to the page.

  1. Create a new local resource bit and select the Pintura CSS file (pintura.css).
  2. Create another local resource bit and select the Pintura JavaScript file (pintura-iife.js).
  3. Create a JavaScript bit and add the following code.
document.addEventListener('change', function (e)  // Store reference to the field to make later code easier to read const field = e.target; // Only intercept fields of type file that accept images and contain a file if ( field.type !== 'file' || !field.files[0] || !/image\/*/.test(field.accept) ) return; // Get reference to parent form const form = field.form; // Edit dropped image with Pintura const editor = pintura.openDefaultEditor( // The image to load src: field.files[0], // Set up custom file upload imageWriter:  store:  // Where to post to url: form.getAttribute('action'), // Which fields to post dataset: (state) => [ // Copy file field name and set value to output image [field.name, state.dest, state.dest.name], // Copy action field value ['action', form.querySelector('[name="action"]').value], ], >, >, >); >);

Now we can link these newly created bits to our “file-upload” shortcode by clicking the “Snippy/Shortcodes” menu item and editing our “file-upload” shortcode. Select the bits we just created and click “Save”.

Refresh the page and select an image, Pintura should open the image and when clicking done the edited image should appear in the WordPress Media Library. Please note that the animation below shows version 6 of the editor.

Security

To make this solution a little bit more secure we can add a WordPress nonce field.

Edit the HTML form like this:

form action=">" method="POST" enctype="multipart/form-data" > > form>

And add the following if statements to the functions.php file so it checks if the form post is valid and came from your own site.

function handle_my_file_upload()  if (empty($_POST))  http_response_code(400); echo 'Nothing data received.'; die(); > if (!wp_verify_nonce($_POST['my_nonce_field'], 'my_file_upload'))  http_response_code(400); echo 'Unknown error.'; die(); > /* The rest of the function stays the same */ >

Conclusion

That’s it! We’re done. These code snippets should give you a good idea of what is required for uploading files with WordPress and how to build uppon it. If you were not familiar with Snippy this should’ve been a nice introduction on how it can help you manage small parts of your WordPress site.

That said. This is still a bare bone solution that can be further build uppon with redirects, upload progress indicators, sending additional form data, and more. I’ll leave that for a future article.

I share web dev tips on Twitter, if you found this interesting and want to learn more, follow me there

At PQINA I design and build highly polished web components.

Make sure to check out FilePond a free file upload component, and Pintura an image editor that works on every device.

Источник

media_handle_upload() │ WP 2.5.0

Загружает переданный в форме файл в папку загрузок WordPress и создает запись о файле в базе данных (добавляет файл в медиатеку WP). Работает c глобальной переменной $_FILES , функции нужно указать индекс массива $_FILES , который содержит данные о загружаемом файле и функция сама загрузит файл в папку загрузок WordPress и создаст запись о вложении в таблице wp_posts в базе данных. Во втором параметре нужно указать id записи (поста), к которой загруженный медиафайл должен быть прикреплен.

require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php';

Когда нужно работать с произвольными данными файла, а не с массовом $_FILES , используйте media_handle_sideload().

Возвращает

Использование

media_handle_upload( $file_id, $post_id, $post_data, $overrides );

$file_id(строка) (обязательный) Индекс элемента массива $_FILES, который содержит данные о принятом файле (название, тип, размер, временное расположение). $post_id(число) (обязательный) ID поста, к которому будет прикреплен медиафайл. Если не нужно, чтобы файл был прикреплен к посту, то укажите в параметре 0 . $post_data(массив) Позволяет перезаписать данные создаваемого вложения. Тут указываются данные которые будут записаны в таблицу wp_posts для создаваемого вложения: post_parent, post_title, post_excerpt и т.д.
По умолчанию: array() (данные по умолчанию) $overrides(массив) Позволяет изменить поведение функции wp_handle_upload(), на основе которой работает текущая функция.
По умолчанию: array( ‘test_form’ => false )

Примеры

#1 Форма загрузки файла и его сохранение

Для начала приведем пример кода формы с полем загрузки файла. Предположительно код установлен в лицевой части сайта:

Убедитесь, что вы используете атрибут enctype=»multipart/form-data» для формы.
Если его не указать, то $_FILES будет пустым и функция media_handle_upload() вернет ошибку.

#2 Создание множественной загрузки файлов в WordPress

WordPress позволяет загружать сразу несколько файлов даже с возможностью drag-and-drop, в Админ-панели. Если вам нужно добавить такую возможность на внешнюю часть сайта, то сделать это не так сложно. Для этого допустим, создадим шаблон страницы (my-upload-page.php) и разместим на нем форму:

Эта форма отправляет данные на свою же страницу (action=»»), поэтому в коде этого же файла (my-upload-page.php) шаблона нужно разместить обработчик, см. пример выше. Добавить свой пример

Список изменений

Код media_handle_upload() media handle upload WP 6.2.2

function media_handle_upload( $file_id, $post_id, $post_data = array(), $overrides = array( 'test_form' => false ) ) < $time = current_time( 'mysql' ); $post = get_post( $post_id ); if ( $post ) < // The post date doesn't usually matter for pages, so don't backdate this upload. if ( 'page' !== $post->post_type && substr( $post->post_date, 0, 4 ) > 0 ) < $time = $post->post_date; > > $file = wp_handle_upload( $_FILES[ $file_id ], $overrides, $time ); if ( isset( $file['error'] ) ) < return new WP_Error( 'upload_error', $file['error'] ); >$name = $_FILES[ $file_id ]['name']; $ext = pathinfo( $name, PATHINFO_EXTENSION ); $name = wp_basename( $name, ".$ext" ); $url = $file['url']; $type = $file['type']; $file = $file['file']; $title = sanitize_text_field( $name ); $content = ''; $excerpt = ''; if ( preg_match( '#^audio#', $type ) ) < $meta = wp_read_audio_metadata( $file ); if ( ! empty( $meta['title'] ) ) < $title = $meta['title']; >if ( ! empty( $title ) ) < if ( ! empty( $meta['album'] ) && ! empty( $meta['artist'] ) ) < /* translators: 1: Audio track title, 2: Album title, 3: Artist name. */ $content .= sprintf( __( '"%1$s" from %2$s by %3$s.' ), $title, $meta['album'], $meta['artist'] ); >elseif ( ! empty( $meta['album'] ) ) < /* translators: 1: Audio track title, 2: Album title. */ $content .= sprintf( __( '"%1$s" from %2$s.' ), $title, $meta['album'] ); >elseif ( ! empty( $meta['artist'] ) ) < /* translators: 1: Audio track title, 2: Artist name. */ $content .= sprintf( __( '"%1$s" by %2$s.' ), $title, $meta['artist'] ); >else < /* translators: %s: Audio track title. */ $content .= sprintf( __( '"%s".' ), $title ); >> elseif ( ! empty( $meta['album'] ) ) < if ( ! empty( $meta['artist'] ) ) < /* translators: 1: Audio album title, 2: Artist name. */ $content .= sprintf( __( '%1$s by %2$s.' ), $meta['album'], $meta['artist'] ); >else < $content .= $meta['album'] . '.'; >> elseif ( ! empty( $meta['artist'] ) ) < $content .= $meta['artist'] . '.'; >if ( ! empty( $meta['year'] ) ) < /* translators: Audio file track information. %d: Year of audio track release. */ $content .= ' ' . sprintf( __( 'Released: %d.' ), $meta['year'] ); >if ( ! empty( $meta['track_number'] ) ) < $track_number = explode( '/', $meta['track_number'] ); if ( is_numeric( $track_number[0] ) ) < if ( isset( $track_number[1] ) && is_numeric( $track_number[1] ) ) < $content .= ' ' . sprintf( /* translators: Audio file track information. 1: Audio track number, 2: Total audio tracks. */ __( 'Track %1$s of %2$s.' ), number_format_i18n( $track_number[0] ), number_format_i18n( $track_number[1] ) ); >else < $content .= ' ' . sprintf( /* translators: Audio file track information. %s: Audio track number. */ __( 'Track %s.' ), number_format_i18n( $track_number[0] ) ); >> > if ( ! empty( $meta['genre'] ) ) < /* translators: Audio file genre information. %s: Audio genre name. */ $content .= ' ' . sprintf( __( 'Genre: %s.' ), $meta['genre'] ); >// Use image exif/iptc data for title and caption defaults if possible. > elseif ( 0 === strpos( $type, 'image/' ) ) < $image_meta = wp_read_image_metadata( $file ); if ( $image_meta ) < if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) < $title = $image_meta['title']; >if ( trim( $image_meta['caption'] ) ) < $excerpt = $image_meta['caption']; >> > // Construct the attachment array. $attachment = array_merge( array( 'post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => $content, 'post_excerpt' => $excerpt, ), $post_data ); // This should never be set as it would then overwrite an existing attachment. unset( $attachment['ID'] ); // Save the data. $attachment_id = wp_insert_attachment( $attachment, $file, $post_id, true ); if ( ! is_wp_error( $attachment_id ) ) < // Set a custom header with the attachment_id. // Used by the browser/client to resume creating image sub-sizes after a PHP fatal error. if ( ! headers_sent() ) < header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id ); >// The image sub-sizes are created during wp_generate_attachment_metadata(). // This is generally slow and may cause timeouts or out of memory errors. wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) ); > return $attachment_id; >

Cвязанные функции

upload download (файловая система file загрузка)

  • download_url()
  • media_handle_sideload()
  • media_sideload_image()
  • size_format()
  • wp_check_filetype()
  • wp_check_filetype_and_ext()
  • wp_convert_hr_to_bytes()
  • wp_get_upload_dir()
  • wp_handle_sideload()
  • wp_handle_upload()
  • wp_max_upload_size()
  • wp_upload_bits()

Загрузка (download upload)

Источник

Читайте также:  Запуск питон скриптов linux
Оцените статью