Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am working on a plugin that constructs a newsletter witch uses a template with a few images.

The images have been uploaded using the Media Library (uploads/current_year/current_month/) and I want to get the images URL by using the image name.

Any way of doing this without iterating over all the images?

I have tried to store the images in the plugin folder but the website uses https and this location is not accessible without authentication.

Any suggestions on different location for storing the images?

share|improve this question

2 Answers 2

I think you should run a custom mySQL query to the wp_posts table, something like -

SELECT ID FROM `wp_posts` where guid like '%filename.jpg';

(of course use $wpdb object to query the databse). Then you will have the postid of that attachment file and you can use wp_get_attachment_url() from the WP API.

share|improve this answer

wp_upload_dir() is perfect. It is the only place where you can expect write permissions.

Store the attachment ID, not a path. Then you get the image with:

wp_get_attachment_url( $attach_id )

Sometimes a user may have deleted the image per media library. To avoid problems with missing files check the return value from wp_get_attachment_url() first. Excerpt from one of my plugins:

/**
 * Returns image markup.
 * Empty string if there is no image.
 *
 * @param  int    $attach_id
 * @return string
 */
protected function get_image_tag( $attach_id )
{

    $img_url = (string) wp_get_attachment_url( $attach_id );

    if ( '' == $img_url )
    {
        return '';
    }

    $img = "<img src='$img_url' alt='' width='$this->width' height='$this->height'>";

    return $img;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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