Upload video from front end programmatically Wordpress - php

I am trying to upload video from front end programmatically in wordpress page.
This is my code:
<?php
if (isset($_POST['uploadvideo'])) {
if ( ! function_exists( 'wp_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' );
}
$uploadedfile = $_FILES['photoContent'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile )
{
$image_url = $movefile["url"];
$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'
);
$listing_post_id = 780 ; // post id
$attach_id = wp_insert_attachment( $attachment, $file, $listing_post_id);
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
/*end file uploader*/
}
}
?>
<form method ="post" action="" name="uploadvideo" enctype="multipart/form-data">
<label for="ug_photo">Your Video Files
<input type="file" value="" name="photoContent" id="ug_photo" class="" multiple="multiple"></label>
<label for="ug_submit_button">
<input type="submit" value="uploadvideo" name="uploadvideo" id="ug_submit_button" class="btn"></label>
</form>
But it is not working. I have hardcoded an post id 780, I will change that later.
Please help. Thanks in advance.

wp_generate_attachment_metadata() won't work if you do not include this file :-
require_once( ABSPATH . 'wp-admin/includes/image.php' );
use wp_upload_bits( $_FILES['picture']['name'], null, #file_get_contents( $_FILES['picture']['tmp_name'] ) ); to upload files other than images

Please try changing the line $uploadedfile = $_FILES['photoContent']; to $uploadedfile = $_FILES['ug_photo']; in your code.

Related

WordPress plugin development : How to upload a file to the default "uploads" directory?

I'm trying to upload files to the default "wp-content/uploads" directory. Have tried almost all the available tags, still not working.
Few of the codes I tried:
$filename = $_FILES["uploadfile"]["name"];
$tempname = $_FILES["uploadfile"]["tmp_name"];
$folder= 'wp_upload_dir()'. $filename; //This code is uploading the file to the "wp-admin" directory
if(move_uploaded_file($tempname, $folder)){$response}
$uploaddir = 'uploads/'; $uploadfile = $uploaddir . $filename;`
if(move_uploaded_file($tempname, $uploadfile))
`
I've coded to save the image in uploads folder for one of my website. please check if this code helps
//taking image in $name_icon
$name_icon = $_POST['myfile'];
// WordPress environment
require( dirname(__FILE__) . '/../../../wp-load.php' );
$wordpress_upload_dir = wp_upload_dir();
$i = 1; // number of tries when the file with the same name is already exists
$profilepicture = $_FILES['myfile'];
$new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
$new_file_mime = mime_content_type( $profilepicture['tmp_name'] );
if( empty( $profilepicture ) )
die();
if( $profilepicture['error'] )
die( $profilepicture['error'] );
if( $profilepicture['size'] > wp_max_upload_size() )
die( 'It is too large than expected.' );
if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
die( 'WordPress doesn\'t allow this type of uploads.' );
while( file_exists( $new_file_path ) ) {
$i++;
$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
}
// looks like everything is OK
if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
$upload_id = wp_insert_attachment( array(
'guid' => $new_file_path,
'post_mime_type' => $new_file_mime,
'post_title' => preg_replace( '/\.[^.]+$/', '', $profilepicture['name'] ),
'post_content' => '',
'post_status' => 'inherit'
), $new_file_path );
// wp_generate_attachment_metadata() won't work if you do not include this file
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate and save the attachment metas into the database
wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
Tested & works

Copy image to my server direct from URL and upload it to Wordpress uploads folder?

I am trying to upload an image through PHP script as mentioned below. I am taking image from the URL;
I have taken reference from this post Actually in my case I want to upload it to WordPress upload folder where post images get upload and you know WordPress creates folder on run-time inside 'wp-content/uploads/' and it uploads image there. So path ($save_path) is not decided on run time.
$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);
I am trying to use WordPress function "media_handle_upload" to upload image instead of "file_put_contents" but I am not getting how I pass file object to this function once i get the file contents ($contents=file_get_contents($url);). Kindly assist.
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
100% working this code:
include_once( ABSPATH . 'wp-admin/includes/image.php' );
$imageurl = '<IMAGE URL>';
$imagetype = end(explode('/', getimagesize($imageurl)['mime']));
$uniq_name = date('dmY').''.(int) microtime(true);
$filename = $uniq_name.'.'.$imagetype;
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($imageurl);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data );
echo $attach_id;
Here is complete example :
// $filename should be the path to a file in the upload directory.
$filename = '/path/to/uploads/2013/03/filename.jpg';
// The ID of the post this attachment is for.
$parent_post_id = 37;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// 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 );
set_post_thumbnail( $parent_post_id, $attach_id );
You can check wp_insert_attachment() for more info

$_FILES returns NULL in WordPress file upload function

So I'm still building the settings page for my theme and I'm busy with the file upload function. The wp_handle_upload function is working but the file is not being grabbed.
This is the registered option:
add_settings_field("upload_logo", "Upload Logo", "logo_display", "theme-options", "section");
register_setting("section", "upload_logo", "handle_logo_upload");
This is the function that set's up the theme page:
function theme_settings_page() {
?>
<div class="wrap">
<h1>Theme Panel</h1>
<form method="post" action="options.php" enctype="multipart/form-data">
<?php
settings_fields("section");
do_settings_sections("theme-options");
submit_button();
?>
</form>
</div>
<?php
}
This is the function that accepts an image:
function logo_display()
{
?>
<form method="post" action="options.php" enctype="multipart/form-data">
<input type="file" name="upload_logo" id="upload_logo" value="<?php echo get_option('upload_logo'); ?>"/>
</form>
<?php
}
This is the function that handles the upload:
function handle_logo_upload() {
if ( !function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$uploadedfile = $_FILES['upload_logo']['submit'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
$wp_filetype = $movefile['type'];
$filename = $movefile['file'];
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename);
echo '<br>';
//return $attach_id;
var_dump($uploadedfile);
//print_r($uploadedfile);
//wp_die('end');
}
return 'fail';
}
When I do I var_dump on the variable $uploadedfile, I get NULL. Why is that?
Here is a screenshot of the settings page for my theme: http://pasteboard.co/yFck7LW.png
This is the empty file that is uploaded when I try to upload something: http://pasteboard.co/yFhrUbB.png
Please help!
Here's the problem:
$uploadedfile = $_FILES['upload_logo']['submit'];
change that to:
$uploadedfile = $_FILES['upload_logo']['name'];

Set featured image to be specific URL, rather than a filename

I'm a C# programmer - but trying to get into PHP.
I'm using a plugin to import Amazon products into a website.
My host however, blocks me from importing the images - which would normally be used as the featured image.
The code below sets the featured image when trying to import the images.
How can I change it to set the featured image, but to use the full URL to the original Amazon image link (I assume it's $image_url):
function set_featured_image( $post_id, $image_url ){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
$filename_ar = explode('.', $filename);
$filename = sanitize_file_name( $filename_ar[0] ).'.'.$filename_ar[1];
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, $post_id );
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 );
set_post_thumbnail( $post_id, $attach_id );
}
Or do I manually have to import the image and link to it locally?
Thanks for any help,
Mark
Is it an option to consider hot-linking the image? Keeps it from sapping bandwidth and storage on your site, and avoids the issue of needing to obtain and store a local copy of the image altogether.

How to differ two uploads in one form with same upload handling?

I have already created a form for my plugin, and it has two upload fields; one for an image and one for a zip-file. They are both using the same upload handler, and I want to save the attachment ID's to the database. The problem is that they use the same upload handler, so the value of the variable with the attachment ID will always be the last upload field. How is the best way to do this? Save in array (first index is first field, second index is second field)? Two upload handler is probably a bit overkill. Any ideas how to solve this in a good way?
This is the function that handles the upload:
function releases_action(){
global $wpdb;
// Upload cover
$uploadfiles = $_FILES['uploadfiles'];
if (is_array($uploadfiles)) {
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
}
As I said, as both upload fields uses the same function, the $attach_ID variable will be the value of the latest upload.
function releases_action(){
global $wpdb;
// Upload cover
$uploadfiles = $_FILES['uploadfiles'];
if (is_array($uploadfiles)) {
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
wp_update_attachment_metadata( $attach_id, $attach_data );
// $ids[]= $attach_id;
// save $attach id here, its correct for this loop, on the next loop it will be different and so on..
}
}
return $ids; // or save here serialize() maybe needed depending on how you are saving.
}

Categories