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 );
Related
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 );
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);
}
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 ?
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";
}
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 );
}