wrong with wp_generate_attachment_metadata() - php

It works (upload , send to db) but
wp_generate_attachment_metadata() returns bad letters whene file uploaded !
some of the wrong charechters :
����JFIF��;CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 90 ��C ��C ����"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�
the code :
if (isset($_FILES['ed_header_logo'] ) && !empty($_FILES['ed_header_logo']['name']) )
{
$filename = $_FILES['ed_header_logo']['name'];
$wp_filetype = wp_check_filetype( basename($filename), null );
$wp_upload_dir = wp_upload_dir();
move_uploaded_file( $_FILES['ed_header_logo']['tmp_name'], $wp_upload_dir['path'] . '/' . $filename );
$url = $wp_upload_dir['url'] . '/' . basename( $filename );
$attachment = array(
'guid' => $url,
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => 'weblogo',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $url, 37 );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $url );
wp_update_attachment_metadata( $attach_id, $attach_data );
}

try this:
if (isset($_FILES['ed_header_logo'] ) && !empty($_FILES['ed_header_logo']['name']) )
{
$uploadedfile = $_FILES['ed_header_logo'];
$upload_name = $_FILES['ed_header_logoe']['name'];
$uploads = wp_upload_dir();
$filepath = $uploads['path']."/$upload_name";
if ( ! function_exists( 'wp_handle_upload' ) )
{
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$upload_overrides = array( 'test_form' => false );
//$attach_id = media_handle_upload( $file, $new_post );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
//print_r($movefile);
if ( $movefile && !isset( $movefile['error'] ) ) {
$file = $movefile['file'];
$url = $movefile['url'];
$type = $movefile['type'];
//media_handle_upload( $file_handler, 0 );
$attachment = array(
'post_mime_type' => $type ,
'post_title' => $upload_name,
'post_content' => 'Image for '.$upload_name,
'post_status' => 'inherit'
);
$attach_id=wp_insert_attachment( $attachment, $file, 0);
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
}

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

Setting the post thumbnail from code fails

I had a non-finished version for setting a post thumbnail from a base64 encoded image (from an API) which i dind't use at the time but now i need it.
function attach_image ( $base64, $post_id, $filename ) {
if ( empty($base64) ) {
return false;
}
$upload_dir = wp_upload_dir();
$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
$decoded = base64_decode($base64) ;
$hashed_filename = md5( $filename . microtime() ) . '_' . $filename;
$image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded );
if( !function_exists( 'wp_handle_sideload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $hashed_filename, $parent_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $hashed_filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
add_post_meta($post_id, '_thumbnail_id', $attach_id, true);
}
This almost work,
The images gets copied to the current wp-content/year/month folder
The image has the hash prepended in the name ( 0acaa00c73c27baa3277ff22ba5acf05_xk35480.jpg )
The image is set as the post thumbnail (for the $post_id )
But the problem is that,
If the image saved is:
wp-content/uploads/2019/09/0acaa00c73c27baa3277ff22ba5acf05_xk35480.jpg
The post thumnail url is:
wp-content/uploads/xk35480.jpg
Note that the year, month and hash are lost. So obviously the thumbnail url returns 404
So the question is, can you spot the problem?
I was able to make it work by prepending wp_upload_dir()['path'].'/' to the wp_insert_attachment and to the wp_generate_attachment_metadata functions but I wonder if it can be done "better"
function attach_image ( $base64, $post_id, $filename ) {
if ( empty($base64) ) {
return false;
}
$upload_dir = wp_upload_dir();
$upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
$decoded = base64_decode($base64) ;
$hashed_filename = md5( $filename . microtime() ) . '_' . $filename;
$image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded );
if( !function_exists( 'wp_handle_sideload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, wp_upload_dir()['path'].'/'.$hashed_filename, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, wp_upload_dir()['path'].'/'.$hashed_filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
add_post_meta($post_id, '_thumbnail_id', $attach_id, true);
}

PHP - Download and set featured image wordpress post

I'am using WP trying to download image from another servee and download, and then i wan to update featured image and my script here :
<?php
include_once ("../wp-load.php");
$post_id = 4376;
$image_url = "https://www.sepatuonline.co.id/wp-content/uploads/raindoz/RSR-006.jpg";
update_images($post_id, $image_url);
function update_images($post_id, $image_url) {
$image_name = 'wp-header-logo.png'; $upload_dir = wp_upload_dir();
$image_data = wp_remote_get($image_url);
$image_data = $image_data['body'];
$image_data = json_decode($image_data, true);
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name );
$filename = basename( $unique_file_name );
if( wp_mkdir_p( $upload_dir['path'] ) ) { $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; }
file_put_contents( $file, $image_data );
$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' );
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
}
But just return broken file, whats wrong ?

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

Categories