RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

Import Remote Images into WordPress and Return Image URL, Image ID, and Image Dimensions

Import Remote Images into WordPress and Return Image URL, Image ID, and Image Dimensions

The WordPress function below - intended to be referenced inside another shortcode function - will import a remote image into your WordPress library. WordPress has a function to handle importing remote images, but I needed the image ID and dimensions, and our function provides for this. Because it's difficult to show the result of our code, I've written a shortcode that serves no real purpose other than to demonstrate how the primary function is used.

The function will likely be referenced by other posts in the future.

The Result

Consider the image header to our neglected FLIGHT website. Our function will import the logo into our WordPress library (inheriting our normal image structure), create all our defined image sizes, query the database for the image ID, and finally, query the database again for the image width and height. Once you retrieve image details it's very important that you record the result in your WP database. Calling the function again will result with the image importing again and again.

Usage is as follows:

1
$url = 'http://www.flight.org/wp-content/themes/wt_spirit/images/logo.png';
2
$result = beliefmedia_import_image($url, $description = 'Image', $src = 0);

Using the demonstration function provided on this page, and assuming we're returning an array rather than just the local URL, we'll return the following:

Array
(
    [html] => https://www.beliefmedia.com.au/wp-content/uploads/2017/09/logo-3.png
    [url] => http://www.flight.org/wp-content/themes/wt_spirit/images/logo.png
    [imgid] => 25067
    [width] => 420
    [height ] => 90
)

The linked example function is for demonstration purposes only and will require modification before it can be applied in any practical way.

WordPress Function

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
 Import Remote Images into WordPress and Return Image URL, Image ID, and Image Dimensions
4
 http://www.beliefmedia.com/import-remote-images-wordpress
5
*/
6
 
7
function beliefmedia_import_image($url, $description = 'Image', $src = 0) {
8
 
9
 global $post;
10
 global $wpdb;
11
 
12
  require_once(ABSPATH . "wp-admin" . '/includes/image.php');
13
  require_once(ABSPATH . "wp-admin" . '/includes/file.php');
14
  require_once(ABSPATH . "wp-admin" . '/includes/media.php');
15
 
16
  /* https://codex.wordpress.org/Function_Reference/media_sideload_image */
17
  $html = media_sideload_image($url, $post->ID, $desc="$description", $return='src');
18
 
19
  $temp['html'] = $html;
20
  $temp['url'] = $url;
21
 
22
  /* Now get image ID */
23
  $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$html'";
24
  $imgid = $wpdb->get_var($query);
25
  $temp['imgid'] = $imgid;
26
 
27
  /* Get attributes */
28
  $attributes = wp_get_attachment_image_src( $imgid, $size = 'full' );
29
  $temp['width'] = $attributes['1'];
30
  $temp['height '] = $attributes['2'];
31
 
32
 return ($src) ? (string) $html : (array) $temp;
33
}

In almost all cases we'll return an array and store that data in the WP database.

A Practical Example

We'll be referencing this snippet when performing tasks such as listing YouTube videos in a tower with accompanying thumbnails. If you choose to store those images locally, you may want to import them into your own WordPress library. As an example of how we might retrieve the remote image, import it into WP, and then return a specific size, consider the following example.

We'll import a YouTube image  associated with one of our FLIGHT videos . The shortcode of [remoteimagedemo url="https://img.youtube.com/vi/vbxl3hc_pL8/0.jpg"] will return the following thumbnail .

Now imported into your WordPress library we'll continue to use your own local copy for subsequent retrievals.

Copy and paste the WordPress function into your theme's functions.php file or, if you sensibly have one installed, your custom functions plugin.

1
<?php 
2
/*
3
 Code to demonstrate the beliefmedia_import_image() function
4
 Import Remote Images into WordPress and Return Image URL, Image ID, and Image Dimensions
5
 http://www.beliefmedia.com/import-remote-images-wordpress
6
 http://www.beliefmedia.com/code/wp-snippets/import-remote-image-demo
7
*/
8
 
9
function beliefmedia_remote_image_demo($atts) {
10
 
11
  extract(shortcode_atts(array(
12
    'url' => '', /* Image URL */
13
    'description' => 'Image',
14
    'source' => 0
15
  ), $atts));
16
 
17
 /* Post ID */
18
 global $post;
19
 
20
  /* DB Image hash */
21
  $hash = 'wp_imp_' . md5($url);
22
 
23
  if ( (get_post_meta($post->ID, $hash, true)) != '') {
24
   $temp = get_post_meta($post->ID, $hash, true);
25
 
26
   } else {
27
 
28
    $temp = beliefmedia_import_image($url, $description, $src = 0);
29
    add_post_meta($post->ID, $hash, $temp);
30
 
31
   }
32
 
33
  /* Get thumbnail URL */
34
  $image_data = wp_get_attachment_image_src($temp['imgid'], 'thumbnail');
35
  $thumbnail = $image_data['0'];
36
 
37
 return '
38
<p align="center"><img src="' . $thumbnail . '" width="' . $image_data['1'] . '" height="' . $image_data['2'] . '">';
39
}
40
add_shortcode('remoteimagedemo', 'beliefmedia_remote_image_demo');

In reality we'd create a means to strip the black bars, we'd apply appropriate image styling and tags, and we would return a default image if wp_get_attachment_image_src() returned false (along with other some other basic error checking). Because the whole exercise is mildly expensive, when we perform this operation for our own (upcoming) YouTube tower code, we cache the resulting HTML with Simple Cache or via the transient API.

Considerations

  • Our primary image shortcode (and that which we advocate for our clients) is performed via an image ID, and the resulting image is sized and cached outside of the WP library. If you're currently a partner, continue to use the methods as described in your Custom WordPress Documentation.
  • To create custom image sizes, use WP's add_image_size() function. If you were to use a YouTube thumbnail, you should create an image size with an aspect ratio of 16:9 (1.777).

Download


Title: Import Remote Images into WordPress
Description: Import Remote Images into WordPress and Return Image URL, Image ID, and Image Dimensions.
  Download • Version 0.2, 717.0B, zip, Category: WordPress Shortcodes

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment