WordPress frontend upload issue - php

In frontend I have created a form that use upload_user_file() to upload files from fronted theme and every image is stored fine in WordPress media library (well it seems like so).
So when I upload a file named test.jpg its relative thumbnails is created and visible in media library.
test-150x150.jpg
test-300x225.jpg
test-1024x768.jpg
The problem I have is when I delete this image from the media library. Only the created thumbnails is deleted and test.jpg is left intact in the upload folder. If I upload this file directly from media library, and then delete it all files is deleted including test.jpg.
Heres the code that stores values in a database and also upload files to the medialibrary. Is there another WordPress function to use? I guess upload_user_file() is not storing image data correctly in database?
global $wpdb;
global $post;
//$table = 'wp_verk1_project'; //$post_slug=$post->post_name;
$table = $wpdb->prefix . "project_name_" . $post_slug=$post->post_name;
$data = array(
'contributorname' => $_POST['yourname'],
'email' => $_POST['email'],
'telephone' => $_POST['telephone'],
'description' => $_POST['description'],
'date' => date('Y-m-d'),
'time' => date('H:i:s'),
'upload' => upload_user_file($_FILES['file']),
'upload2' => upload_user_file($_FILES['file2']),
'upload3' => upload_user_file($_FILES['file3']),
'upload4' => upload_user_file($_FILES['file4']),
'upload5' => upload_user_file($_FILES['file5']),
'rate' => '0'
);
$format = array(
'%s',
'%s'
);
$success = $wpdb->insert($table, $data, $format);
if ($success) {
header("Location: " . get_bloginfo('url') . "/thank-you/");
exit();
}
edit_user_file():
function upload_user_file( $file = array() ) {
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 {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
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;
}
Kind regards
Johan

I manage to solve my own question.
I digged into the WordPress core-files.
Ireplaced the following line:
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
with this:
$attachment_id = wp_insert_attachment( $attachment, $filename );
In wp_postmeta, meta_value for the upload was set to the complete url (http://sitenamen.com/wp-content/upload/2014/12/file.jpg) while it should be stored like this: 2014/12/file.jpg
Now all files is deleted.

Related

Image is showing in wordpress localhost uploads folder but not updating in wordpress media library (wp dashboard))

I'm trying to upload image using wp custom template in child theme but when i upload any image. It appears in "E:\Xamp\htdocs\website\wp-content\uploads\2019\10" but not uploaded to wp dashboard media library.
I'M NOT ALLOWED TO USE ANY PLUGIN FOR THIS TASK.
$post_id = wp_insert_post($my_post);
if(isset($_FILES['file']['name'])){
if(! function_exists('wp_handle_upload')){
require_once(ABSPATH.'wp-admin/includes/file.php');
}
$uploadfile = $_FILES['file'];
print_r($uploadfile);
$upload_overrides = array('test_form' => false );
$moveupload = wp_handle_upload($uploadfile,$upload_overrides);
if($moveupload && ! isset($moveupload['error'])){
echo "</Pre";
wp_update_attachment_metadata( $post_id, $moveupload);
print_r($moveupload);
echo "Post/>";
}else{
echo $moveupload['error'];
}
}
Can try out another piece of code here:
--------------------------
$upload_overrides = array( "test_form" => false );
$uploaded_file = wp_handle_upload ($file, $upload_overrides);
if( isset( $uploaded_file ["file"] )) {
$file_name_and_location = $uploaded_file ["file"];
$file_title_for_media_library = $title;
$attachment = array(
"post_mime_type" => $uploaded_file_type,
"post_title" => addslashes( $file_title_for_media_library ),
"post_content" => "",
"post_status" => "inherit"
);
if( ! is_null( $post )) {
if ( ! is_numeric( $post )) {
$post = $post->ID;
} // if ()
$attachment ['post_parent'] = $post;
} // if ()
$id = wp_insert_attachment( $attachment, $file_name_and_location );
require_once( ABSPATH."wp-admin/includes/image.php" );
$attach_data = wp_generate_attachment_metadata( $id, $file_name_and_location );
wp_update_attachment_metadata( $id, $attach_data );
} // if ()
Uploading files into the wp-content/uploads won't show up in the Media Library , those media ID's needs to be there in the database to show up in the Media Library.
If you already have files in the uploads folder and want to add them into the database
But this is not the correct solution instead fix the permissions issue for that uploads folder.
Thanks
i solved it by using custom php code.
$upload = wp_upload_bits($_FILES["file"]["name"], null, file_get_contents($_FILES["file"]["tmp_name"]));
$filename = $upload['file'];
$wp_filetype = wp_check_filetype($filename, null );
// print_r($filename);
$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, $filename, $post_id );
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 );
set_post_thumbnail( $post_id, $attach_id );

add user meta for featured image

I'm developing a site in which a user is able to capture his/her pic(via .getusermedia) which updated as the post thumbnail.
The problem is that the post thumbnail gets updated for all users - I want the post thumbnail to be updated only for that particular user
function Generate_Featured_Image( $filename, $parent_post_id ){
require('/wp-load.php');
$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_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$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 );
wp_update_attachment_metadata( $attach_id, $attach_data );
//add_user_meta( $current_user_id, $parent_post_id, $attach_id);
set_post_thumbnail( $parent_post_id, $attach_id );
}
script.php
Generate_Featured_Image( $addroot.$current_user_id.$extimage, 88 );
// addroot=path ext-extension(.jpg) (this is name of file saved)
i tried to user add_user_meta to accomplish the task but couldn't even get a start
UPDATE
<?php
// $filename is succesfully saved as currentuserid+.jpg.
$addroot = '/wp-content/uploads/2016/09/';
$current_user_id = get_current_user_id();
$extimage = '.jpg';
$filename = $addroot.$current_user_id.$extimage;
$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, 0 );
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 );
update_user_meta( get_the_ID(), $filename , $_POST[ $filename ] );
?>
how to proceed further by calling the image to by $attach_id from usermeta and displayinf it to user as thumbnail- unable to figure this step
You can't really set a different featured image for post based on a user. There is just one post, therefore only one featured image for it.
If you want to display a different image, based on which user is viewing the post, save that use wp_insert_attachment( $attachment, $filename, 0) to insert attachment without binding it to the post. Then save that $attach_id to the usermeta table. Then, when user is viewing that post, simply get $attach_id with get_user_meta and display that image (you can use wp_get_attachment_url for example) instead of featured image of the post.
UPDATE
First, saving user meta should look like this
update_user_meta($current_user_id, '_avatar_id', $attach_id);
Second, in the beginning, you should check if user is logged in with is_user_logged_in function.
Third, you should check for user had avatar before and remove it (I mean, why store their old one after they have a new one, right?) like so:
$old_attach=get_user_meta($current_user_id, '_avatar_id', true);
if(is_numeric($old_attach))
{
wp_delete_attachment($old_attach, true);
}
Your final code to save avatar should look like:
if (is_user_logged_in())
{
$addroot = '/wp-content/uploads/2016/09/';
$current_user_id = get_current_user_id();
$extimage = '.jpg';
$filename = $addroot . $current_user_id . $extimage;
$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_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $filename, 0);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $filename));
$old_attach = get_user_meta($current_user_id, '_avatar_id', true);
if (is_numeric($old_attach))
{
wp_delete_attachment($old_attach, true);
}
update_user_meta($current_user_id, '_avatar_id', $attach_id);
}
else
{
//show error here or something
}
Now, to access it, you can write a simple function, like this:
function get_user_avatar()
{
if (is_user_logged_in())
{
$avatar_id = get_user_meta(get_current_user_id(), '_avatar_id', true);
if (is_numeric($avatar_id))
{
return'<img src="' . wp_get_attachment_url($avatar_id) . '" alt="User avatar"/>';
}
else
{
return '<img src="url_to_your_default_avatar" alt="User avatar"/>';
}
}
return false;
}

Upload image to wordpress and saving details in db

I want to upload an image to wordpress via a php script completely outside wordpress. I know what tables i have to insert data to. However I've noticed that if i pass through the normal way wordpress creates various sizes of the image and also save this in db. Is there a way to simulate the upload of the image using a script completely outside wordpress.
Yes, it would be something like this:
<?php
header('Response: HTTP/1.1 200 OK');
define('WP_USE_THEMES', false);
require('../../../../wp-load.php');
$uploadedfile = $_FILES['image'];
if($uploadedfile['size'] > 0){
$upload_overrides = array( 'test_form' => false );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$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);
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 );
die(json_encode(array('type'=>'error', 'text' => 'Ok', 'error' => 0)));
}else{
die(json_encode(array('type'=>'error', 'error' => 1)));
}
}
die(json_encode(array('type'=>'error', 'error' => 2)));
}
?>
Please note that i´ve pasted my code, you´ll have to work with it a little bit ;)

WordPress not adding files properly to Media Library

I'm busy making my own theme in WordPress. I am using a handler to add media files to WordPress library. It is located in functions.php and looks like this:
function handle_logo_upload()
{
if ( !function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$uploadedfile = $_FILES['file'];
$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);
//wp_die('end');
}
return 'fail';
}
At the bottom of this code, you can see var_dump($uploadedfile); This is returning NULL.
Also, when I upload an image using the theme function, i get a file looking like this in the media library: http://pasteboard.co/wgpYJRq.png
What the first thing that comes to mind?

how to upload an image on ACF with update_field on wordpress

I have a form, which has an upload ($_FILES['watch_photo']) field.
I have looked around and came to put this function together.
It basically takes all relevant information so it is re-usable in the future, it will return an array of the $pid, and URL of the file, when it is done.
The problem is that ACF has not provided much information how to add images to it's fields using update_field() http://www.advancedcustomfields.com/resources/functions/update_field/
function my_update_attachment($f,$pid,$t='',$c='') {
wp_update_attachment_metadata( $pid, $f );
if( !empty( $_FILES[$f]['name'] )) { //New upload
require_once( ABSPATH . 'wp-admin/includes/file.php' );
$override['action'] = 'editpost';
$file = wp_handle_upload( $_FILES[$f], $override );
if ( isset( $file['error'] )) {
return new WP_Error( 'upload_error', $file['error'] );
}
$file_type = wp_check_filetype($_FILES[$f]['name'], array(
'jpg|jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
));
if ($file_type['type']) {
$name_parts = pathinfo( $file['file'] );
$name = $file['filename'];
$type = $file['type'];
$title = $t ? $t : $name;
$content = $c;
$attachment = array(
'post_title' => $title,
'post_type' => 'attachment',
'post_content' => $content,
'post_parent' => $pid,
'post_mime_type' => $type,
'guid' => $file['url'],
);
foreach( get_intermediate_image_sizes() as $s ) {
$sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => true );
$sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options
$sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options
$sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options
}
$sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes );
foreach( $sizes as $size => $size_data ) {
$resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] );
if ( $resized )
$metadata['sizes'][$size] = $resized;
}
$attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $pid - for post_thumbnails*/);
if ( !is_wp_error( $id )) {
$attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_meta );
}
return array(
'pid' =>$pid,
'url' =>$file['url']
);
// update_post_meta( $pid, 'a_image', $file['url'] );
}
}
}
and then I used the following code:
to create a post and then
upload then use my_update_attachment to process the image
and finally update the advanced custom field
The code:
$args= array( 'post_type' => 'watches', 'post_status' => 'publish' );
$watch = wp_insert_post($args);
$att = my_update_attachment('watch_image',$watch);
update_field('field_512e085a9372a',$att['url'],$watch);
What am I missing? any help would be greatly appreciated.
I had the same problem, you almost had it right, which helped me as well.
looked at ACF and the update_field accepts attachment ID as oppose to the the, pid or url
You can replace the return array:
return array(
'pid' =>$pid,
'url' =>$file['url']
);
With the following array:
return array(
'pid' =>$pid,
'url' =>$file['url'],
'file'=>$file,
'attach_id'=>$attach_id
);
and then change
update_field('field_512e085a9372a',$att['url'],$watch);
with the following
update_field('field_512e085a9372a',$att['attach_id'],$watch);
should this line
if ( !is_wp_error( $id )) {
be
if ( !is_wp_error( $attach_id )) {
Check this plugin:
https://wordpress.org/plugins/acf-frontend-display/
Create ACF form with frontendUploader field (plugin extention)
Add your ACF form into post and with post admin panel use checkbox to view on front

Categories