WordPress | Upload files through the frontend

Problem:
Uploading files to WordPress is fairly easy using the media_handle_sideload function.
However, outside the admin panel, it is an accident waiting to happen.
First, because the required includes are not, well, included.
Second, because, usually there may be permissions issues.
Also, if the method fails, it will often not throw any exceptions, so many of the suggestions out there to handle exceptions are not really helpful.

Solution(s):

1) Edit the permissions of the wp-content\uploads folder to 777.

2) Before media_handle_sideload, make sure you add the code below.

if ( !function_exists('media_handle_upload') ) {
   require_once(ABSPATH . "wp-admin" . '/includes/image.php');
   require_once(ABSPATH . "wp-admin" . '/includes/file.php');
   require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}

Full example:
$filename = "test.png";

$file_array = array(
            'name' => '/wp-content/' . $filename ,
            'tmp_name' => '/wp-content/' . utf8_decode($filename)
        );
//upload a single file, with a custom name, without any specific post attachment
$return = media_handle_sideload($file_array, 0, $filename);
if ( is_wp_error($return) )
  echo $return->get_error_message();

Source:
http://wordpress.org/support/topic/media_handle_sideload-not-working-halts-execution

Comments

Popular posts from this blog

Breaking down document locking in SharePoint

Working around X-Frame-Options for iframes

Document ID not being generated