10

I have some folder with images in /wp-content/uploads. I also have a plugin file in /wp-content/plugins. I want to retrieve the images stored in /wp-content/uploads and use them in the plugin file.

I have tried

echo'<img src="../../USER_PHOTOS/ronny'" href="#"></img>';

can someone show me how I can get the path to these images? thanks.

5 Answers 5

9

If I'm not mistaken, you may want to try the wp_uploads_dir function, like so:

$uploads = wp_upload_dir(); 

echo '<img src="' . esc_url( $uploads['baseurl'] . '/USER_PHOTOS/ronny/' ) . '" href="#">';
4

Unfortunately there is a documented bug where wp_upload_dir() does not honor https (ssl). My suggestion is to write a wrapper to remove the protocol from the returned URL to make it adaptable to the environment:

function wp_upload_dir_url() {
  $upload_dir = wp_upload_dir();
  $upload_dir = $upload_dir['baseurl'];
  return preg_replace('/^https?:/', '', $upload_dir);
};
echo(wp_upload_dir_url() . '/2017/01/my-img.jpg');
// outputs something like '//mysite.test/wp-content/uploads/2017/01/my-img.jpg'
// which is perfectly acceptable as an img src

If you are concerned about the performance hit of using preg_replace() multiple times, then set a constant in your functions.php file:

define('WP_UPLOAD_DIR_URL', wp_upload_dir_url() . '/');
2

Dan S points out a trac ticket where wp_upload_dir() does not support https. I've not found this to be the case on my sites, but if it does affect you, then you can add a filter to upload_dir and manually return the correct protocol based on the is_ssl() conditional.

add_filter( 'upload_dir', function( $upload_dir ){
  return array_map( function( $value ) {
    return is_ssl() ?
      str_replace( 'http://', 'https://', $value ) :
      str_replace( 'https://', 'http://', $value );
  }, $upload_dir );
}, 10, 1 );

Then you can continue using wp_upload_dir() as you always have.

As noted here, unless you have specific performance concerns you should use https://.

1

I found the answer. I used wp_upload_dir(); wordpress codex

0

This is what I used to access an image file named "rock_01.jpg" uploaded to the wordpress folder "uploads/complete-theme/"

<?php $upload_dir = wp_upload_dir(); ?>
<img src="<?php echo $upload_dir['baseurl'] . '/complete-theme/rock_01.jpg'; ?>" />

It worked as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.