WordPress not adding files properly to Media Library - php

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?

Related

How to save a picture from URI given in a JSON feed

I read a JSON feed in PHP from an external website. In this feed I have to pictures URI. I’m writing a wordpress plugin to create posts from this JSON feed but I would be able to download the pictures and save them inside my WordPress uploads folder.
Any idea how I can do this?
function to save the image:
function insert_attachment_from_url($url, $parent_post_id = null) {
if( !class_exists( 'WP_Http' ) )
include_once( ABSPATH . WPINC . '/class-http.php' );
$http = new WP_Http();
$response = $http->request( $url );
if( $response['response']['code'] != 200 ) {
return false;
}
$upload = wp_upload_bits( basename($url), null, $response['body'] );
if( !empty( $upload['error'] ) ) {
return false;
}
$file_path = $upload['file'];
$file_name = basename( $file_path );
$file_type = wp_check_filetype( $file_name, null );
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
$wp_upload_dir = wp_upload_dir();
$post_info = array(
'guid' => $wp_upload_dir['url'] . '/' . $file_name,
'post_mime_type' => $file_type['type'],
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment( $post_info, $file_path, $parent_post_id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $parent_post_id, $attach_id );
return $attach_id;
}
and to run the function:
$image = 'YOUR_IMAGE_URL';
insert_attachment_from_url( $image );

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 );

wp_insert_attachement not returning value in wordpress

Here, I am attaching the image to post (custom field) by using wp_insert_attachment function but unfortunately i am not getting the attachment id from wp_inset_attachment function. Here is my code.
function jda_upload_image( $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']);
/* Here I am not getting the 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 );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
It took time. I tried with your code but got stuck. So I did that with the following code. It works fine for me. Perhaps works for you as well.
Change the code as per your requirement.
$file = $_FILES['logo'];
if(!empty($file)) {
handle_logo_upload($file);
}
function handle_logo_upload($file){
if ( !function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
require_once ( ABSPATH . 'wp-admin/includes/image.php' );
$uploadedfile = $file;
$upload_overrides = array(
'test_form' => false,
);
if(!empty($uploadedfile['name'])) {
$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);
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
echo '<br>';
var_dump($uploadedfile);
return "pass";
}
}
return "fail";
}

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 frontend upload issue

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.

Categories