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.
Related
I am using the Board Game Geek API in order to pull in various data. One piece of data I want is the image.
For example, here is an API call for a particular board game:
https://boardgamegeek.com/xmlapi2/thing?id=169786&stats=1
When I get the response via my ajax call, I am able to grab the image url within the xml via:
var image_url = $(data).find("image")[0].textContent;
However: at that point I'm stumped. I want to upload the image that is located at that url, but I do not know how to upload the image via a form.
In wordpress: the only way I know how to upload images is if the image already exists on my computer. In that scenario, I have the following input:
<label for='board_game_image></label>
<input type="file" name="board_game_image" id="board_game_image" multiple="false"></input>
This input creates the "Choose Files" button to upload an image from your computer. Once the form is submitted, I use media_handle_upload to save the image within the uploads directory and create the relevant database records. Unfortunately: this process appears to not work when the image does not already exist on your computer, but instead exists somewhere on the internet (i.e. the image exists via the url).
Question: How can I upload an image via a wordpress front-end form when the image does not exist on my computer? Instead: all I have is the url of where the image exists on the internet.
You should include the image link on your form,
e.g.
var image_url = $(data).find("image")[0].textContent;
//assign the value to hidden input
$('#imgURL').val( image_url );
then add something like this on your form
<input type="hidden" id="imgURL" name="imageURL">
I'm not sure how you handle your form submission, but you can do something like below to process the image after submission.
First, save the image on uploads folder
$imgurl = $_REQUEST['imageURL']; // get the img url from the submitted data
$imginfo = pathinfo($imgurl); //get the url information
$filename = $imginfo['filename'].'.'.$imginfo['extension']; // extract the image filename
$updir = wp_upload_dir(); // get upload directory
$uploadedfile = $updir['path'] . '/' . $filename; // create upload image location & file name
$image= file_get_contents( $imgurl ); // get the image actual content
$saved = fopen($uploadedfile, 'w'); // open the image file
fwrite($saved, $image); // write image conent
fclose($saved); // close image
Your image is now uploaded and stored on wp-content uploads folder, and the exact location is at $uploadedfile
However, the image is still not added on media library as it doesn't have any database entry connected to that image,
Now simply use wp_insert_attachment function to link that image into a database and it will show on media library,
just check that documentation and you'll see an example of linking $uploadedfile file to media library, you can do something like,
$filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
$img_id = wp_insert_attachment( $attachment, $uploadedfile );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $img_id, $uploadedfile );
wp_update_attachment_metadata( $img_id, $attach_data );
can you please check below 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;
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);
Good evening. I've written a function to programmatically insert a Wordpress post for each of our YouTube videos, using a foreach loop.
Everything is working wonderfully, until I get to inserting the post thumbnail. I am using a function that automatically handles the uploading and inserting of a thumbnail, and associating it with a post (below):
function Generate_Featured_Image($image_url, $post_id) {
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($post_id.'-'.$image_url);
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 );
$res1 = wp_update_attachment_metadata( $attach_id, $attach_data );
$res2 = set_post_thumbnail( $post_id, $attach_id );
}
This function does work, but for some odd reason, it only uploads the image from the last video in the loop. For example, if I have 5 videos, 5 posts will be created. Each containing it's own specific information, but the post thumbnail will all be the image from the last (5th) video. None of them have their own thumbnail.
Here's a slimmed down verson of my function that creates the posts:
function createYouTubePost() {
...some other code...
$JSON = file_get_contents('https://www.googleapis.com/youtube/v3/search?order='.$api_order.'&part='.$api_part.'&channelId='.$channel_id.'&maxResults='.$max_results.'&key='.$api_key);
$json_data = json_decode($JSON, true);
foreach ($json_data['items'] as $data) {
$video_id = $data['id']['videoId'];
$video_title = $data['snippet']['title'];
$video_description = $data['snippet']['description'];
$video_thumb_url = $data['snippet']['thumbnails']['high']['url'];
$video_thumb_width = $data['snippet']['thumbnails']['high']['width'];
$video_thumb_height = $data['snippet']['thumbnails']['high']['height'];
$video_publish_date = $data['snippet']['publishedAt'];
$args = array(
'post_title' => substr($video_title, 0, strrpos($video_title, '(')),
'post_content' => $video_description,
'post_status' => 'publish',
'post_type' => 'download',
);
if (!if_download_exists(substr($video_title, 0, strrpos($video_title, '(')))) {
$new_post_id = wp_insert_post($args, true);
if ($new_post_id == 0) {
echo '<br>Could not create the post.';
var_dump($new_post_id);
}
else {
Generate_Featured_Image($video_thumb_url, $new_post_id);
...lots of code to update various post_meta fields...
echo '<br>New post created.<br>';
var_dump($new_post_id);
}
}
}
}
Here you can see the media attachments and how they're all the same:
And here are the individual posts that were created:
As you can see, each image is assigned to it's respective post, but the image is the same.
I have even tried setting the filename of each picture with a unique ID so that they're all different, but that didnt help. I have also confirmed that the image url's that I am passing to the function are all different.
My question is, if I am using my function Generate_Featured_Image() in a foreach loop, and provding it with unique information, why is it only using the last picture in the loop?
Thanks for any help!
I went with another solution. Wordpress' media_sideload_image() function works and is a more straight forward solution for my situation.
Here is the function that I'm now using to assign a thumbnail to a post:
function generateFeaturedImage($image_url, $post_id) {
// required libraries for media_sideload_image
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// $post_id == the post you want the image to be attached to
// $video_thumb_url == the vimeo video's thumb url
// $description == optional description
// load the image
$result = media_sideload_image($image_url, $post_id);
// then find the last image added to the post attachments
$attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));
if (sizeof($attachments) > 0) {
// set image as the post thumbnail
set_post_thumbnail($post_id, $attachments[0]->ID);
}
}
Here's the link to the stack exchange solution that I found.
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 );
I’m creating a custom post submit form for wordpress and at the moment I can create the post and have the image uploaded and attached to the post but the next step im struggling at - I’m looking to have the uploaded image automatically displayed on the post, ive looked into the featured image option but just can’t get it to work
$my_post = array();
$my_post['post_title'] = $newid;
$my_post['post_content'] = $imageurl1.$imageurl.$config_basedir.$uploaddir.$id . ".gif". $imageurl2;
$my_post['post_author'] = 1;
$my_post['post_status'] = draft;
$my_post['post_category'] = array($a);
// Insert the post into the database
$post_id = wp_insert_post($my_post);
//
$wp_filetype = wp_check_filetype(basename($id . ".gif"), null );
$attachment = array();
$attachment['post_mime_type'] = $wp_filetype['type'];
$attachment['post_title'] = $newid;
$attachment['post_content'] = '';
$attachment['post_status'] = 'inherit';
$attach_id = wp_insert_attachment($attachment, $id . ".gif", $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_redirect( site_url()."?p=$post_id" ); exit();
Any help is appreciated
Use set_post_thumbnail. You can pass in the post object or ID. Thumbnail ID is the media attachment ID.
set_post_thumbnail( $post, $thumbnail_id );