Get the Official WPSaviour App Now!

BlogTutorials

How to Add a Featured Image from a URL in WordPress

Usually it is best to dynamically add a featured image to a put up or a personalized put up kind from one different server than the one your WordPress arrange is working. And in addition you’re coping with a regular state of affairs: learn the way to do it?

In any case on this case, it is best to seize the featured image from the second server, receive it to your particular person server, inside the add folder, and assign it to the correct put up. In the 1st step we’ll create a model new put up dynamically, after which we’ll care for the featured image.

Step 1: Create a Put up Dynamically

To dynamically create a put up, it is best to use the wp_insert_post() function. You can place the code beneath in an “IF” assertion, in every other case each time an internet web page is loaded it ought to create a model new put up. Not that useful.

// Register Put up Info
$put up = array();
$put up['post_status']   = 'publish';
$put up['post_type']     = 'put up'; // is normally a CPT too
$put up['post_title']    = 'My New Put up';
$put up['post_content']  = 'My new put up content material materials';
$put up['post_author']   = 1;

// Create Put up
$post_id = wp_insert_post( $put up );

Working this code will merely create a model new put up. Now it’s time in order so as to add the featured image.

Step 2: Add the Featured Image

In order so as to add the featured image from a URL, we now need to make use of some WordPress options:

  • wp_upload_dir() : to retrieve the uploader folder path
  • wp_mkdir_p() : to create folder and set permissions
  • wp_check_filetype() : to check attachment format
  • sanitize_file_name() : to format attachment file determine
  • wp_insert_attachment() : to create attachment
  • wp_generate_attachment_metadata() : to generate attachment metadata
  • wp_update_attachment_metadata() : to interchange attachment metadata
  • set_post_thumbnail() : to assign attachment as put up featured image

And now proper right here is the code. I commented each movement with the intention to see exactly what’s going down when this script is working.

// Add Featured Image to Put up
$image_url        = 'http://s.wordpress.org/mannequin/pictures/wp-header-logo.png'; // Define the image URL proper right here
$image_name       = 'wp-header-logo.png';
$upload_dir       = wp_upload_dir(); // Set add folder
$image_data       = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate distinctive determine
$filename         = basename( $unique_file_name ); // Create image file determine

// Confirm folder permission and description 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 );

// Confirm image file kind
$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 );

// Embody image.php
require_once(ABSPATH . 'wp-admin/consists of/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 place up
set_post_thumbnail( $post_id, $attach_id );

What’s fascinating on this code is that you’d have the ability to place it in a loop. As an illustration to import posts from a CSV file, or an XML file. That’s really extremely efficient and truly useful, nevertheless don’t overlook  one issue: in no way ever use this script in your options.php file with out inserting a conditional tag sooner than in every other case you’ll get a lot of of current posts created in a matter of minutes!

Download The WPSaviour App Now

Related posts
Beginner’s GuideBlogTutorials

Use Gutenberg like a pro with keyboard shortcuts

Beginner’s GuideBlogSecurityWordPress Security

A Simple Explanation of SSL Certificate Errors & How to Fix Them

Beginner’s GuideBest WordPress PluginsBlog

9 Best A/B Split Testing Plugins for WordPress

Best WordPress PluginsBlog

7 Best Plugins for Tracking User Activity in WordPress

Sign up for our Newsletter and
stay informed

Fear Of Missing Out?

Sign up with your email address to receive WordPress tips and updates
SUBSCRIBE NOW
Terms and Conditions apply
close-link
Click Me