How do I link to external images in my WP posts - php

I am scraping a site and putting data in my WP site.
There are lots of images in those posts.
I want that when importing that scraped data into my WP site,
I want to link images into my site directly from that external URL instead of downloading image to my server.
I am grammatically importing scraped data to my site.
Here is that part of adding image
// for image
$ins_q = "INSERT INTO wpxw_posts (post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status, "
. "comment_status, ping_status,"
. "post_password, post_name, to_ping, pinged, post_modified,post_modified_gmt, post_content_filtered,post_parent,"
. "guid,menu_order,post_type,"
. "post_mime_type,comment_count) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$sth = $conn->prepare($ins_q);
if (!$sth->execute(array(
$post_author, $date, $date, "", sanitize_title_with_dashes($image_name), "", "inherit", "open", "closed", '',
str_replace(".", "-", $image_name), '', '', $date, $date, '', $post_id,
"http://photos2.zillowstatic.com/p_f/ISdc6hruhctopo0000000000.jpg"
, 0, "attachment", "image/jpeg", 0
))) {
echo "<h1>Error</h1>";
print_r($sth->errorInfo());
exit();
}
}
MY PROBLEM is that when adding external link to image, images do not show on my post. How can I show images from external resources?

// Add Featured Image to Post
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$filename = basename($image_url); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );

Related

How to store image uploaded from form as featured image in post?

I have an html form in front end in WordPress page. A user uploads the image in the form which should be set as featured image in CPT.
This is the upload field in the form:
<input id="uploadBtn" type="file" class="upload" name="uploadBtn"/>
I have tried this code :
// Add Featured Image to Post
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png';// Define the image URL here
$image_name = 'wp-header-logo.png';
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name); // Generate unique name
$filename = basename( $unique_file_name ); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $new_post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $new_post_id, $attach_id );
It works well if I have image url, name and such. However, I need to make it work for any image that user uploads. Is there any way to get image url and name from $_FILES? Any help would be appreciated. Thanks!
You need either post object or post ID for the set_post_thumbnail() function. The function wp_insert_post() will return post id on success. You can use that post id to set the thumbnail image.
Here is the modification for your last couple of lines
$post_id = wp_insert_post( $my_post );
if(!$post_id){
// post insertion was failed. Handle it here
}
//Set Image as thumbnail
set_post_thumbnail($post_id, $attach_id);

PHP on Server downloads empty images

I've got a php function that downloads youtube thumbnails to the server, and it works fine on my local version, however as soon as it gets uploaded to the server all of the .jpg files that it downloads are empty.
function download_thumbnail() {
preg_match('/src="(.+?)"/', get_field('youtube_link'), $matches); //Pull the URL of the video out of the iframe generated by ACF
preg_match("/embed\/(.+)\?/", $matches[1], $vid_id); //Pull the ID of the video from the URL
$download_url = "https://img.youtube.com/vi/".$vid_id[1]."/maxresdefault.jpg"; //Use the standard youtube link to get the max res thumbnail
$uploads = wp_upload_dir();
$path = $uploads['path']."/"; //Get the upload path
$filename = $vid_id[1].'.jpg'; //Set the filename as the ID of the video
$save_as = $path.$filename; //Full path of the created file
if(!file_exists($save_as)) { //Check if file exists
$ch = curl_init($download_url); //Initialize the PHP cURL to the youtube page
$fp = fopen($save_as, 'wb'); //Start the path link
curl_setopt($ch, CURLOPT_FILE, $fp); //Download the image to the path link
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$filetype = wp_check_filetype( basename( $save_as ), null ); //Check the file type
$attachment = array( //Create neccessary wordpress data to the image
'guid' => $uploads['url'] . '/' . basename( $save_as ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $save_as ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $save_as, get_the_ID() ); //Add neccessary wordpress data to the image
require_once( ABSPATH . 'wp-admin/includes/image.php' ); //Make sure that the image gets registered as an image
$attach_data = wp_generate_attachment_metadata( $attach_id, $save_as ); //Generate more meta data
wp_update_attachment_metadata( $attach_id, $attach_data ); //Attatch the meta data
set_post_thumbnail( get_the_ID(), $attach_id ); //Set image as the featured image
}
}
Any help / insight is appreciated.
Thanks

How to set featured image programmatically from url?

I have some post id's and I want to set these posts' featured images from same url.
Here is my adding post codes:
$catid = get_cat_ID("XX Cat");
$my_post = array();
$my_post['post_title'] = $title;
$my_post['post_content'] = $description;
$my_post['post_status'] = 'publish';
$my_post['post_author'] = 1;
$my_post['post_category'] = array( $catid );
$post_id = wp_insert_post( $my_post );
Example: post_id = 1 I want to set featured image to: example.com/image.png
How can I do this?
You can set an image as post featured thumbnail when it is in your media library. To add an image in your media library you need to upload it to your server.
try this code:
// Add Featured Image to Post
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here
$image_name = 'wp-header-logo.png';
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
$filename = basename( $unique_file_name ); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );
ref url : http://www.wpexplorer.com/wordpress-featured-image-url/
Modified as your requirement:
or that purpose ignore WordPress standard and upload your all post single image on your custom folder and add this image path or direct external image url into post as extra attribute meta field and when you will show post on your theme then just use your img with help of post id.
demo code:
for setting image
<?php
update_post_meta ( 7, 'imgkey', 'www.url.path' );//7 is post id
?>
for getting image on your theme page where you want to show it
<?php
$img_value = get_post_meta( get_the_ID(), 'imgkey', true );
?>
<img src="<?php echo $img_value?>">
Note if you are new in WordPress post custom meta fields then read this article:
https://codex.wordpress.org/Custom_Fields
or
unofficial article about custom fields: https://premium.wpmudev.org/blog/creating-custom-fields-manually
if you have to load an image and then assign as thumbnail of the post, the quicker way is to use media_sideload_image and then set_post_thumbnail
https://developer.wordpress.org/reference/functions/media_sideload_image/
$url = "http://url-of-the-image.jpg";
$post_id = [post id]
$desc = "image description";
$image = media_sideload_image( $url, $post_id, $desc,'id' );
set_post_thumbnail( $post_id, $image );
Just to complement #Naraj answer, if you are working in an external file, remember to add:
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
if you do not add that you will get an error message saying that media_sideload_image is undefined.

Copy image to my server direct from URL and upload it to Wordpress uploads folder?

I am trying to upload an image through PHP script as mentioned below. I am taking image from the URL;
I have taken reference from this post Actually in my case I want to upload it to WordPress upload folder where post images get upload and you know WordPress creates folder on run-time inside 'wp-content/uploads/' and it uploads image there. So path ($save_path) is not decided on run time.
$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);
I am trying to use WordPress function "media_handle_upload" to upload image instead of "file_put_contents" but I am not getting how I pass file object to this function once i get the file contents ($contents=file_get_contents($url);). Kindly assist.
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
100% working this code:
include_once( ABSPATH . 'wp-admin/includes/image.php' );
$imageurl = '<IMAGE URL>';
$imagetype = end(explode('/', getimagesize($imageurl)['mime']));
$uniq_name = date('dmY').''.(int) microtime(true);
$filename = $uniq_name.'.'.$imagetype;
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($imageurl);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data );
echo $attach_id;
Here is complete example :
// $filename should be the path to a file in the upload directory.
$filename = '/path/to/uploads/2013/03/filename.jpg';
// The ID of the post this attachment is for.
$parent_post_id = 37;
// Check the type of file. We'll use this as the 'post_mime_type'.
$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, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
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 );
set_post_thumbnail( $parent_post_id, $attach_id );
You can check wp_insert_attachment() for more info

Wordpress - Upload image programmatically, width and height are 0

I made a function which allows users to upload image to my wordpress site. Uploading works fine, but when I open a post with this uploaded image, the image doesn't show up. When I opened it in Firebug I noticed that image width and height is 0.
How can I upload image so it show up like I uploaded it with Media Library form.
This is my code:
if(isset($_FILES["image"])) {
if (!function_exists('wp_handle_upload')) require_once(ABSPATH . 'wp-admin/includes/file.php');
$uploadedfile = $_FILES['image'];
$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);
set_post_thumbnail($pageid, $attach_id);
}
}
Edit:
When I manually add width: 100% in Firebug, the image show up
I found a solution for this problem.
After the image was uploaded, meta data was not updated. So at the end of this function I added this:
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 );
This code updates the meta data for this image, therefore, Wordpress can find its dimensions.

Categories