I'm using the wp dropzone plugin trying to tweak things a little to create a a front end image uploader that sets the current post as the attachments parent.
The plugin as is works really well but by default no matter where I locate the uploader any attachments are marked as un attached in my media library.
I can't for the life of me work out why this isn't working as I've tried all standard calls to get the current post id and set this as the parent.
The full php plugin file is quite extensive so I've included the core section which operates the attachment insertion. See my progress what I have below.
Importantly if I set the post parent as the actual id number; '240' for example it attaches to the called post. I'm looking to attach this to the current post.
/**
* Handle ajax file upload to media library.
*
* #since 1.0.0
*/
function wpday_dz_ajax_upload_handle() {
if (!empty($_FILES) && wp_verify_nonce($_REQUEST['wpday_dz_nonce'], 'wpday_dz_protect')) {
// Including file library if not exist
if (!function_exists('wp_handle_upload')) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
// Uploading file to server
$movefile = wp_handle_upload($_FILES['file'], ['test_form' => false]);
// If uploading success & No error
if ($movefile && !isset($movefile['error'])) {
$filename = $movefile['file'];
$filetype = wp_check_filetype(basename($filename), null);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
'post_mime_type' => $filetype['type'],
'post_parent' => $post->ID,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
);
// Adding file to media
$attachment_id = wp_insert_attachment($attachment, $filename);
// If attachment success
if ($attach_id) {
require_once ABSPATH . 'wp-admin/includes/image.php';
// Updating attachment metadata
$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
wp_update_attachment_metadata($attach_id, $attach_data);
}
$message['error'] = 'false';
$message['data'] = wp_get_attachment_url($attach_id);
} else {
$message['error'] = 'true';
$message['data'] = $movefile['error'];
}
wp_send_json($message);
}
}
add_action('wp_ajax_wpday_dz', 'wpday_dz_ajax_upload_handle');
add_action('wp_ajax_nopriv_wpday_dz', 'wpday_dz_ajax_upload_handle');
EDIT:
Have tried:
$id = get_the_ID();
// If uploading success & No error
if ($movefile && !isset($movefile['error'])) {
$filename = $movefile['file'];
$filetype = wp_check_filetype(basename($filename), null);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($filename),
'post_mime_type' => $filetype['type'],
'post_parent' => $id,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
);
Still returns unattached
I downloaded WP Dropzone and had a look at the code. AFAICT the function you are working on is called via AJAX, once a file is dropped/uploaded. In that case, there is no "post" in the current request - you're in an AJAX file unrelated to any post.
So the question becomes how to get the ID of the post that called the current AJAX request. I found this SO answer which answers that:
$url = wp_get_referer();
$post_id = url_to_postid( $url );
Related
I am using Google Drive API to upload Excel files. I did the API connection correctly. Create a folder and upload the excel file correctly. I can see both of them in my google drive. But, the excel file is empty.. What am I missing here?
my code is below:
$path = "uploads/school_info.xlsx"; //file that I am uploading, inside a folder of my website.
$folder_id = create_folder("School_".$_POST['submit_uid'], "****folder-id****");
$file_name = "School 1";
$success = insert_file_to_drive( $path, $file_name, $folder_id);
// This will insert file into drive and returns boolean values.
function insert_file_to_drive( $file_path, $file_name, $parent_file_id = null ) {
$service = new Google_Service_Drive( $GLOBALS['client'] );
$file = new Google_Service_Drive_DriveFile();
$file->setName( $file_name );
if( !empty( $parent_file_id ) ){
$file->setParents( [ $parent_file_id ] );
}
$result = $service->files->create(
$file,
array(
'data' => file_get_contents($file_path),
//'mimeType' => 'application/octet-stream',
'mimeType' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', //works but still empty excel
)
);
$is_success = false;
if( isset( $result['name'] ) && !empty( $result['name'] ) ){
$is_success = true;
}
return $is_success;
}
ok I found what was the problem. As I wrote in my code above, I had a relative path
$path = "uploads/school_info.xlsx";
when I changed it to full path like this:
$path = "https://www.example.com/uploads/school_info.xlsx";
everything works as expected
thank you all for your time
Answer
I have successfully uploaded a .xlsx file with the following code. Apparently it is very similar to yours, I just change the mimeType and add the uploadType. Once the file is uploaded, from the UI version of Drive, I can access and view the contents of the file. In case it still fails, please repeat the process by downloading a sample file from here.
Code
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setName('test.xlsx');
$data = file_get_contents('file_example_XLSX_50.xlsx');
$result = $service->files->create($file, array(
'data' => $data,
'mimeType' => 'application/vnd.ms-excel',
'uploadType' => 'multipart'
));
I have a lot of advanced custom fields. There are three image types between them. I have added ACF text fields with add_post_meta. But I can't add the images.
Here is my code sample
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['new_post'] )) {
$title="New Property for Sale";
$custom_tags = $_POST['tax_input']; //load thread tags (custom tax) into array
$post = array(
'post_title'=>$title,
'post_content' => $_POST['property_description'],
'tax_input' => $custom_tags,
'post_status' => 'pending',
'post_type' => 'property'
);
$post_id = wp_insert_post($post);
//send our post, save the resulting ID
if($post_id){
add_post_meta($post_id, 'type', $_POST['acf']['field_60338ebdd3ca4'], true);
add_post_meta($post_id, 'locality', $_POST['acf']['field_603374e8f8d62'],true);
add_post_meta($post_id, 'address', $_POST['acf']['field_6034ed6a0cd29'], true);
add_post_meta($post_id, 'facing', $_POST['acf']['field_6034eda30cd2b'],true);
add_post_meta($post_id, 'bed_number', $_POST['acf']['field_60337452f8d5f'], true);
add_post_meta($post_id, 'balconies', $_POST['acf']['field_6034f2180cd2c'], true);
//send the user along to their newly created post
}
}
I have added the featured image of the post.
if ( $_FILES['image']['name']!="" ) {
$upload = wp_upload_bits($_FILES["image"]["name"], null, file_get_contents($_FILES["image"]["tmp_name"]));
// $post_id = $post_id; //set post id to which you need to set featured image
$filename = $upload['file'];
$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'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
if ( ! is_wp_error( $attachment_id ) ) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
set_post_thumbnail( $post_id, $attachment_id );
}
}
I have to add more two images with ACF. Please Help me.
This is the most straight away full code on WP codex to upload to Media:
https://developer.wordpress.org/reference/functions/media_handle_upload/
So, try creating this file inside a wordpress page template and after attaching you will have to set the ID on your ACF metadata
<?php
if (
isset( $_POST['my_image_upload_nonce'], $_POST['post_id'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
&& current_user_can( 'edit_post', $_POST['post_id'] )
) {
// The nonce was valid and the user has the capabilities, it is safe to continue.
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress handle the upload.
// Remember, 'my_image_upload' is the name of our file input in our form above.
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
echo "ERROR";
} else {
// The image was uploaded successfully!
echo "Image ID is: " . $attachment_id;
//Now set your image ACF field to the $attachment_id
// My case because its a user metadata update:
//update_user_meta( $userID, 'YOUR_IMAGE_NAME_ACF_FIELD_HERE!!', $attachment_id );
// update post meta of your ACF field with the new attachment id
update_post_meta ( $_POST['post_id'], 'YOUR_IMAGE_NAME_ACF_FIELD_HERE!!' , $attachment_id );
}
} else {
// The security check failed, maybe show the user an error.
}
?>
<!-- HTML code for uploading this single file -->
<form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
<input type="file" name="my_image_upload" id="my_image_upload" multiple="false" />
<input type="hidden" name="post_id" id="post_id" value="55" />
<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
<input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Upload" />
</form>
i want change file upload name and add the name of user that upload it.
This my function.php
if ( ! function_exists( 'upload_user_file' ) ) :
function upload_user_file( $file = array(), $title = false ) {
require_once ABSPATH.'wp-admin/includes/admin.php';
$file_return = wp_handle_upload($file, array('test_form' => false));
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])){
return false;
}else{
$user = wp_get_current_user();
$username = $user->display_lastname;
$filename = $username . $file_return['file'];
return $filename;
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_content' => '',
'post_type' => 'attachment',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
if($title){
$attachment['post_title'] = $title;
}
$attachment_id = wp_insert_attachment( $attachment, $filename );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
endif;
i try with $filename = $username . $file_return['file']; but don't work.
wp_handle_upload accepts an array of overrides, and one of the arguments is unique_filename_callback where you can specify a custom function to rename the file.
Try something like this:
1: Add a function to functions.php to rename the file as you want it, e.g.
function my_custom_filename($dir, $name, $ext){
$user = wp_get_current_user();
/* You wanted to add display_lastname, but its not required by WP so might not exist.
If it doesn't use their username instead: */
$username = $user->display_lastname;
if (!$username) $username = $user->user_login;
$newfilename = $username ."_". $name; /* prepend username to filename */
/* any other code you need to do, e.g. ensure the filename is unique, remove spaces from username etc */
return $newfilename;
}
2: Then in your upload_user_file(), specify your custom callback function in the wp_handle_upload overrides, e.g.
$overrides = array(
'test_form' => false, /* this was in your existing override array */
'unique_filename_callback' => 'my_custom_filename'
);
/* pass your overrides array into wp_handle_upload */
$file_return = wp_handle_upload($file,$overrides);
UPDATE:
To get the new filename in the upload_user_file function, you can get it from the "url" in the $file_return array that's returned by wp_handle_upload:
$newfilename = basename($file_return["url"]);
I am writ plugin for WordPress. It sends a link to the images on the PHP file (Ajax).
The array consists of 10 photos.
obj.photos.push({ img_url: img_url, source: source, photo_text: photo_text, tag: tag });
var data_insert = {
action: 'instapin_insert',
data: obj
};
$.ajax({
type: 'POST',
url: '/wp-content/plugins/instapin/ajax.php',
data: data_insert,
});
Next, the file takes a picture and the script loads to the cloud with Google (Google Drive).
<?php
session_start();
session_write_close();
require_once('../../../wp-config.php');
global $service;
if(class_exists('INSTAPIN'))
{
$instapin = new INSTAPIN();
}
$google_drive = get_option('instapin_drive');
$photos_array = $_POST['data']['photos'];
// Создаём объект записи
$instapin_post = array(
'post_title' => 'Название записи',
'post_content' => '',
'post_status' => 'draft',
'post_author' => 1,
'post_category' => array(0)
);
// Вставляем запись в базу данных
$post_id = wp_insert_post( $instapin_post );
if($google_drive == 'on'){
$folder = get_option('google_upload_folder');
$found = false;
$files = $service->files->listFiles();
foreach ($files['items'] as $item) {
if ($item['title'] == $post_id) {
$folder_insert_photo = $item['id'];
$found = true;
break;
}
}
if($found == false){
$file = new Google_Service_Drive_DriveFile();
//Setup the Folder to Create
$file->setTitle($post_id);
$file->setDescription('Photo folder: post_id - ' . $post_id);
$file->setMimeType('application/vnd.google-apps.folder');
//Set the ProjectsFolder Parent
$parent = new Google_Service_Drive_ParentReference();
$parent->setId( $folder );
$file->setParents(array($parent));
//create the ProjectFolder in the Parent
$createdFile = $service->files->insert($file, array(
'mimeType' => 'application/vnd.google-apps.folder',
));
$folder_insert_photo = $createdFile->id;
$instapin->insertPermission($service, $folder_insert_photo, 'id', 'anyone', 'reader');
}
$count = 1;
$photo = new Google_Service_Drive_DriveFile();
$parent_folder = new Google_Service_Drive_ParentReference();
foreach($photos_array as $item){
if($count == 40){
break;
}
$img_url = strtok($item['img_url'], '?');
$image_url = str_replace("s150x150/", "", $img_url);
$image_data = file_get_contents($image_url); // Get image data
$filename = basename($image_url); // Create image file name
$wp_filetype = wp_check_filetype( $filename, null );
$MimeType = $wp_filetype['type'];
$seo_name = $item['tag'] . '_' . $count . '.jpg';
//Setup the Folder to Create
$photo->setTitle($seo_name);
$photo->setDescription('Photo: ' . $image_url);
$photo->setMimeType($MimeType);
$parent_folder->setId( $folder_insert_photo );
$photo->setParents(array($parent_folder));
// Try to upload the file, you can add the parameters e.g. if you want to convert a .doc to editable google format, add 'convert' = 'true'
$createdPhoto = $service->files->insert($photo, array(
'data' => $image_data,
'mimeType' => $MimeType,
'uploadType'=> 'multipart'
));
$instapin->insertPermission($service, $createdPhoto->id, 'id', 'anyone', 'reader');
$filePath = "GoogleDrive/{$folder_insert_photo}/{$seo_name}";
$fullFile = "https://googledrive.com/host/{$folder_insert_photo}/{$seo_name}";
print_r($fullFile);
$count++;
}
}
?>
But when I send an AJAX post to upload 10 photos, all admin panel and front. Nothing can be done and go until the download is complete (the script works).
But when I post to download 10 photos, all admin panel and front crashes (hangs). Nothing can be done and go until the upload is finished (the script works).
How to make this multi-tasking? So the admin panel and front continue to work, and the script is working in the background.
I am trying to receive files from a webservice and save them into wordpress but I have following issues,
Some of the files will be uploaded but they are corrupted and I can't open them, although their webservice address is correct.
It shows the following errors (although it shows these errors but upload the files anyway, which is good :D but I am wondering why I am receiving them).
Notice: Constant ABSPATH already defined in /Applications/MAMP/htdocs/wordpress/wp-load.php on line 22
Fatal error: Call to undefined function wp_generate_attachment_metadata() in /Applications/MAMP/htdocs/wordpress/wp-content/plugins/myproject/Myclasses/retrieve_2334.php on line 95
My Code:
ini_set( 'display_errors', TRUE );
error_reporting( E_ALL );
require("/Applications/MAMP/htdocs/wordpress/wp-load.php");
$pos = strrpos($Address, "&f=");
$loc = substr($Address, $pos + 3);
$Address = "http://dev.piction.com/v60/" . $Address;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_URL, $Address);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$upload_dir = wp_upload_dir();
$location= $upload_dir['basedir']. "/" . $loc;
try{
$location= $upload_dir['path']. "/" . $loc;
$wp_filetype = wp_check_filetype($loc, null );
$fullpathfilename = $upload_dir['path'] . "/" . $loc;
$fileSaved = file_put_contents($location, $output);
if ( !$fileSaved ) {
throw new Exception("The file cannot be saved.");
}
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $loc),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $upload_dir['url'] . "/" . $loc
);
$attach_id = wp_insert_attachment( $attachment, $fullpathfilename, 0 );
if ( !$attach_id ) {
throw new Exception("Failed to save record into database.");
}
//require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullpathfilename );
wp_update_attachment_metadata( $attach_id, $attach_data );
} catch (Exception $e) {
$error = '<div id="message" class="error"><p>' . $e->getMessage() . '</p></div>';
}
echo 'Photo is uploaded';
It does seem as if you're including a file twice, that would explain why you're getting the "already defined" errors.
Try removing the require() statement in the third line of your code and see if it works, as it seems as if that file is already being included somewhere else in your script.
Try changing to require_once("/Applications/MAMP/htdocs/wordpress/wp-load.php"); as you get the already defined notice it might indicate you have already included wp-load.php.
Also you need to uncomment the line //require ( ABSPATH . 'wp-admin/includes/image.php' ); to be able to use wp_generate_attachment_metadata()