upload image with wordpress rest api - wordpress

I am having trouble uploading an image with the WordPress REST API (WP-API). Can someone provide some sample code. Basically I have an image that I got from a service and I'm showing in an <img> tag. Now I need to take that image and save it in the media library using javascript.
Alternatively (not using WP-API) if there is a plugin that would do that, I can pass the url for the image to get is saved in the media library.
Thanks

You can use the wp_insert_attachment if API is not preferred. Source
Ignore the $parent_post_id if the media library is not post specific.
You can retrieve the image url using this trick: Retrieve images and then use the variable for $filename
// $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 );

Related

Upload file to custom folder wordpress

I have searched extensively unsuccessfully for an answer to this one.
I want to upload files from Contact Form 7 to a folder in the root.
I can upload the files to the upload folder but that is not satisfactory.
I found code which would change the folder location, but cannot see how to load the attachment to this file.
$folderPath = "/candidates//candidate_id/photos/";
mkdir(ABSPATH.$folderPath, 0777, true);
$filename = $image_name;
if ($filename > '') {
require(ABSPATH . 'wp-admin/includes/admin.php');
$wp_filetype = wp_check_filetype(basename($filename), null);
$attachment = array(
'guid' => $wp_upload_dir['url'] . '' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filename, $newpostid);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
wp_update_attachment_metadata($attach_id, $attach_data);
//Define the new Thumbnail can be also a ACF field
update_post_meta($newpostid, "_thumbnail_id", $attach_id);
}
The new directory appears but the images still end up in the uploads folder.
I cannot see where to define the new folder path in the if ($filename condition.
I can now upload to the custom folder but the file permission of image is 0400.
How can we change that?
Code as follows:
'$folderPath = "/candidates//candidate_id/photos/";
mkdir(ABSPATH.$folderPath, 0777, true);
$filename = $image_name;
if ($filename > '') {
require(ABSPATH . 'wp-admin/includes/admin.php');
$wp_filetype = wp_check_filetype(basename($filename), null);
$attachment = array(
'guid' => $wp_upload_dir['url'] . '' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filename, $newpostid);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $filename);
wp_update_attachment_metadata($attach_id, $attach_data);
//Define the new Thumbnail can be also a ACF field
update_post_meta($newpostid, "_thumbnail_id", $attach_id);
}
The new directory appears but the images still end up in the uploads folder.
I cannot see where to define the new folder path in the if ($filename condition.
I have tried the following which uploads to new directory but photo has permission 0400. How can I change to 0644?
`
$folderPath = "/candidates/".$time."/photos/";
mkdir(ABSPATH.$folderPath, 0755, true);
$destination= ABSPATH.$folderPath;
// save any attachments to a temp directory
if(strlen($image_name) > 0 and !ctype_space($image_name)) {
$mail_attachments = explode(" ", $image_name);
foreach($mail_attachments as $attachment) {
$uploaded_file_path = ABSPATH . 'wp-content/uploads/wpcf7_uploads/' . $attachment;
$new_filepath = $destination .'/'. $attachment;
rename($image_location, $new_filepath);
}
}`
Here is what I came up with,
function contactform7_before_send_mail( $form_to_DB ) {
global $wpdb;
$form_to_DB = WPCF7_Submission::get_instance();
if ( $form_to_DB )
$formData = $form_to_DB->get_posted_data();
$uploaded_files = $form_to_DB->uploaded_files(); // this allows you access to the upload file in the temp location
$time = /*date("dmY")."".*/time() ;
if (!empty($formData[Photo])){
$image_name = $formData[Photo];
//$image_name = $time.".jpg";
} else {$image_name="";}
$image_location = $uploaded_files[Photo];
if (!empty($formData[Photo])){
$folderPath = "/candidates/".$time."/photos/";
} else {$folderPath= "/empty/index.php/";}
mkdir(ABSPATH.$folderPath, 0755,true);
$destination= ABSPATH.$folderPath;
// save any attachments to a temp directory
$new_filepath = $destination .'/'. $image_name;
rename($image_location, $new_filepath);
chmod($new_filepath, 0644);

Image upload by image URL or image Link in WordPress

How to upload a image by image URL or link of the image in WordPress media library by programming.
You can do that by passing the $_REQUEST['image'] via URL , by doing the following.
// $filename should be the path to a file in the upload directory.
$filename = $_REQUEST['image'];
// 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 );
Just skip the part you don't need , like set the image to post -> set_post_thumbnail() , I have added it for better reference to attach the image to post.

How can I put these codes into function.php in WordPress?

I want to upload file with Chinese character to a WordPress website. However, the name of the file is gibberish. I have searched the question and found some solutions. One is to modify the //wp-admin/includes/file.php
function wp_handle_upload( &$file, $overrides = false, $time = null ) {
//….
// Move the file to the uploads dir
//$new_file = $uploads['path'] . “/$filename”;
$new_file = $uploads['path'] . “/” . iconv(“UTF-8″,”GB2312″,$filename);
//…
//return apply_filters( ‘wp_handle_upload’, array( ‘file’ => $new_file, ‘url’ => $url, ‘type’ => $type ), ‘upload’ );
return apply_filters( ‘wp_handle_upload’, array( ‘file’ => $uploads['path'] . “/$filename”, ‘url’ => $url, ‘type’ => $type ) , ‘upload’);
}
As I know, it changes the encoding of the filename. But I want to put it in the function.php in the theme folder. What can I do ?

wp_generate_attachment_metadata outputting contents of file instead of writing to file

I'm working on a form that will add images to the Wordpress media library and everything is going peachy, except for creating additional images at smaller sizes. The output is happening inside the WP_Image_Editor class in the multi_resize function and subsequently the _save function. The call to imagetruecolortopalette seems to be the culprit.
The output looks like this:
�PNG IHDR��<q� IDATx���w�%�u�����{�}��IA$(QL&iR����)[a%J���^����|����G^�u��ʒ쵨d[�LS��3��D�`��ͼ|�����?���t��$e�m�|���+�:�wN�V�}� ��xB��㝣�k��1�w߽(���O?�k�Kh�1�`��:�W����S�C����MӠ�b0��C)����])�1�=���ֶ�{��Z��c8�Whex��)��S��t�t���x�,�X��b< ����W������D��j��1u]3(G�#��t��4�W�9��0Z�]��#��TUM��ІAiP^����_�JO)�NFC�����(��K�b��[^s+?���GSM�F����(LAU5�|y����-eY��k��(�v���9�����(epΡ�B)0ư���ц�p�1���M������0��T>��S[YE{���#�yE���BkMY�-a���R�%km$��};��`#UU���-�y�c=��꺦i��n'/\�Ok�����X;emu����7.Q�cAԾkO�Hl�j�w��"9����w�=*�XM\���L��a.\�4X[QU�z���q���]Di�x��t:ƹ�\�?c�.�q�� EY�6�Oo��yH�i��8稪 �\�~�:�T{�1&֡0Fǹr4M�2k-�ɔ��(˂rP&��#�� ��n�$ ��e��i®q��%�K��v�����I.^�Ą��Zkq�kz���eپ�1EAQV+EQ��=s �M=��I�6��k�j��F�ё#Q� �^iq�� �K�v���v��]R75�6J��};1F�}�s���¢�����'O�����`LJ�u�������AK(ι����i;MӴ���E���bKp���� ����>�� ~kF�;��E��t�uK�a'��1��`#w�;�L:̕��!/�����>^�IO ��ӮJm��pc-Mc�(EK�iPi����T�>�DY�P�`L���Z�� �J���4
Normal Wordpress uploading and resizing via the admin or Gravity forms works perfectly fine, but my function causes the error.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$upload_overrides = array( 'test_form' => false );
// http://codex.wordpress.org/Function_Reference/wp_handle_upload
$movefile = wp_handle_upload( $_FILES['image'], $upload_overrides );
if ( $movefile ) {
// http://codex.wordpress.org/Function_Reference/wp_insert_attachment
$wp_filetype = wp_check_filetype( basename( $movefile['url'] ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $movefile['url'] ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $movefile['url'] ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $movefile['url'] );
$attach_data = wp_generate_attachment_metadata( $attach_id, $movefile['url'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
$result = array(
'id' => $attach_id,
'resized' => $resized,
'test' => $wp_upload_dir
);
echo json_encode( $result );
exit;
}
Can anyone point me in the right direction?
To clarify the solution (since it took me a WHILE to figure it out): you have to pass wp_generate_attachment_metadata a relative directory path, not a URL path with http:// on the front.
So instead of:
$attach_data = wp_generate_attachment_metadata( $attach_id, $movefile['url'] );
It should be:
$attach_data = wp_generate_attachment_metadata( $attach_id, ($wp_upload_dir['path'] . '/' . basename( $movefile['url'] )) );
Note that I used wp_upload_dir's path attribute and not its url attribute.
wp_generate_attachment_metadata requires a directory path rather than the file URL which I was passing.
Maybe do not installed imagemegick? because this function use imagmagick for resize pictures to thumbnails try in console:
~$ apt-get install imagemagick php5-imagick
don't forget restarting apache

How To Properly Generate and Update Metadata Image Information In Wordpress

I am using a plugin to extract EXIF image data from images uploaded using a form on my wordpress site. As of now it properly uploads and inserts the image into the media library, but I dont think it is generating any metadata information and updating it. I know this because it used to work with another method I was using, but after I upgraded some plugins,it all stopped working and I can't seem to fix it... What is wrong below that might not be allowing the metadata info to generate from the uploaded image? I get this error on the attachment page:
Notice: Undefined variable: metadata in /mnt/soco-app/forms/wp-content/themes/twentytwelve/image.php on line 25
//Add uploaded image to media library
add_action("gform_after_submission", "post_submission", 10, 2);
function post_submission($entry) {
if($_FILES['input_5']) {/**TURN WP_DEBUG OFF WHEN FIXED**/
$filename = $entry[5];
$wp_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' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$parent_post_id = 9; //ID of Parent Page
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
//require_once(ABSPATH . 'wp-includes/post.php');
//update_post_meta( $parent_post_id, '_wp_attachment_metadata', $attach_data );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
Use the wp_generate_attachment_metadata function.
This function generates metadata for an image attachment. It also creates a thumbnail and other intermediate sizes of the image attachment based on the sizes defined on the Settings_Media_Screen.
http://codex.wordpress.org/Function_Reference/wp_generate_attachment_metadata

Resources