I'm creating a user-submitted post tool for a Wordpress site.
The user can enter an image URL and I want it to be added to the post along with other content like title and post content.
I've got this working using a regular image attachment. I create the post and then attach the image using this script:
$files = $_FILES['upload_attachment'];
$file = array(
'name' => $files['name'],
'type' => $files['type'],
'tmp_name' => $files['tmp_name'],
'error' => $files['error'],
'size' => $files['size']
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$userPost);
}
But how can I do the same thing using insert_attachment() or similar but with a URL?
I think you can use file_get_contents() and file_put_contents(). You'd probably have to do something like this:
file_put_contents('your_file_on_server.xxx', file_get_contents('http://someurl.com/filename.xxx'));
This would download the file from the specified url and save it to your server. From there you can slightly modify your original code to attach it to a post.
Related
I am building a form and where te user can upload a file. Since I am using Drupal I am using the managed_file. The file is being uploaded but I cannot seem to get the filename out of the form... This is my code
Buildform:
$form['formfile'] = array(
'#type' => 'managed_file',
'#name' => 'formfile',
'#title' => t('File'),
'#upload_validators' => $validators,
'#upload_location' => 'public://trainingrequests/',
);
Submit
drupal_set_message($form_state->getValue('formfile'));
I have literally tried everything.
You first need to get the entity ID of the File entity, then load the entity:
$formfile = $form_state->getValue('formfile');
if ($formfile) {
$oNewFile = File::load(reset($formfile));
$oNewFile->setPermanent();
drupal_set_message('Filename: ' . $oNewFile->getFilename());
}
You can browse the source code of the File entity in your file system: core/modules/file/src/Entity/File.php
I have a custom form, with a field for the user to upload an image file (their logo). In the form validate hook, I've implemented file_save_upload, which is continually returning false. I can see that the file is in fact being saved in the correct location on upload, so why isn't file_save_upload working?
The form field:
$form['company_logo'] = array(
'#type' => 'managed_file',
'#title' => t('Company Logo'),
'#description' => t('Allowed extensions: gif png jpg jpeg'),
'#upload_location' => 'public://uploads/',
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
// Pass the maximum file size in bytes
//'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
),
);
The validation hook:
$file = file_save_upload( 'company_logo' , array(), 'public://uploads/', FILE_EXISTS_RENAME);
if (!$file) {
form_set_error('company_logo', t('Unable to access file or file is missing.'));
}
The managed file element handles moving the uploaded file for you, so there's no need to call file_save_upload() manually.
You're getting a NULL return because of these lines in file_save_upload():
// Make sure there's an upload to process.
if (empty($_FILES['files']['name'][$source])) {
return NULL;
}
As the file's already been processed there's nothing for the function to do.
You can persist the file entry by adding a submit handler to the form and using code similar to
$file = file_load($form_state['values']['company_logo']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
I am using the Meta Box plugin for Wordpress. I can successfully create fields in the cms for users to upload images. I would like to extend this in two ways:
First, I would like a delete confirmation when users remove an image from the image gallery
Here is the code:
$meta_boxes[] = array(
'id' => 'project_media',
'title' => 'Project Media',
'pages' => array( 'project' ),
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => 'Media Gallery',
'desc' => 'Images should be sized to 983px x 661px',
'id' => $prefix . 'project_media_gallery',
'type' => 'image'
)
);
This creates upload functionality in the custom post type where users can add images to a slideshow. The problem is if the user accidentally clicks the delete button, there is no confirmation to make sure it is deleted. Can I somehow extend the plugin through functions and call an alert when this button is clicked? Something that does not involve editing the WP core?
Second, the base functionality requires the user to upload an image from their local machine. Is there a way to tap into the Media Library for this?
No idea how to even start tackling this one.
To answer the first question
First, I would like a delete confirmation when users remove an image from the image gallery
You can do that by calling a custom script file from the functions.php.
function alert_delete() {
if(is_admin()){
wp_register_script( 'alert_delete', get_bloginfo('template_url'). '/js/alert_delete.js', array('jquery'));
wp_enqueue_script('alert_delete');
}
}
and create a file named alert_delete.js in the js directory of your theme.
alert_delete.js:
// admin delete check
jQuery(document).ready(function(){
jQuery(".rwmb-delete-file").click(function() {
if (!confirm("Are you sure? This process cannot be undone.")){
return false;
}
});
});
In response to the second question...
Second, the base functionality requires the user to upload an image
from their local machine. Is there a way to tap into the Media Library
for this?
Get the latest version of the Meta Box Plugin first.
then change
'type' => 'image'
to
'type' => 'image_advanced'
which will allow you to upload from the existing Media Gallery or a new file from your computer.
I am creating a module in Drupal 7. If I want to format a UNIX timestamp into a date I can use the format_date function, like so:
$date = format_date($node->created, 'custom', 'j F Y');
Is there also a function I can reference to format an image? Say my database query returns
picture-4-136576449.png
from a table and I want to transform it into:
<img src="/images/picture-4-136576449.png />
is there a function to do it? Thanks.
If you are trying to convert a URI to a URL, you are doing it wrong.
$uri = 'public://images/my-photo.png';
$url = file_create_url($uri);
// $url should be publicly accessible URL now.
If you know the path to the image relative to Drupal root, use
$url = url('path/to/image.png', array('alias' => FALSE));
You can theme an image using theme('image', $variables).
ex:
<?php
print theme('image', array('path' => 'path/to/image.png',
'title' => t('Some title'), //optional
'alt' => t('Some alt text'), //optional
));
You can see the other variables at theme_image() function doc page.
I am building a theme with ability to upload custom background images but now I am stuck at a point.
How do I properly add FILE field in drupal form via theme-setting.php and after that how can I get public url to this file in my template files??
In your theme_form_system_theme_settings_alter hook you need to add the following form element:
$form['theme_settings']['background_file'] = array(
'#type' => 'managed_file',
'#title' => t('Background'),
'#required' => FALSE,
'#upload_location' => file_default_scheme() . '://theme/backgrounds/',
'#default_value' => theme_get_setting('background_file'),
'#upload_validators' => array(
'file_validate_extensions' => array('gif png jpg jpeg'),
),
);
This will save the file id to your theme settigns variable 'background_file', notice that i set the upload location to theme/backgrounds, this will be inside your files folder.
Finally you'll get the complete URL to the file with file_create_url:
$fid = theme_get_setting('background_file');
$image_url = file_create_url(file_load($fid)->uri);
Edit:
In your template.php you can add in the theme_preprocess_page hook the variable so all the tpl's can access it, this is how:
function theme_preprocess_page(&$variables, $hook) {
$fid = theme_get_setting('background_file');
$variables['background_url'] = file_create_url(file_load($fid)->uri);
}
Hope this helps! :D