0

I'm developing an plugin which downloads an image from an FTP server and places that image in a subfolder of the plugin (like: wp-content/plugins/ftpdownload/download/:id"/image.jpg, where :id is the id from which server the image is downloaded (multiple server support))

With n shortcode (like [ftpimage id='id']) the image must be shown on the page/post/widget.

I use this code

$server->image = plugin_dir_path(__FILE__) . "download/" . $server->id ."/" .$server->ftp_file;

to get the path of the image, but that is not working, because [image] contains the full path to the image like :\xampp\htdocs\bouwfilm\wp-content\plugins\ftpdownload/download/2/therm.jpg

How can I get the right path to the image, so I can use it to show the image?

echo '<img src="' . $server->image . '" />';
  • 1
    I suggest you use the native WordPress uploads folder. That is the only folder that has guaranteed write permission. – Jack Johansson May 30 '17 at 22:08
0

You might want to use the media_media_sideload_image() function. This function will fetch an image from a URL and upload it for you. Take a look into this custom function:

function upload_image_from_url($image_url, $post_id, $title) {
    $img_name = basename ($image_url);
    global $wpdb;
    $query = "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value = '$img_name'";
    $id = $wpdb->get_var($query);
    if (is_numeric($id)) {
        return $id;
    } else {
        $attachment_src = media_sideload_image( $image_url, $post_id, $title,'src' );
        $query = "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value = '$img_name'";
        $id = $wpdb->get_var($query);
        return $id;
    }
}

What the above function does, is to search the database to see if the image is already uploaded. If not, it will upload the image into the library and return it's ID, which then can be used later by wp_get_attachment_url() to get the URL.

You can tweak this function not to depend on $post_id or $title ( by detaching the attachment from the post after it's uploaded) to get what you demand.

This is safe, and guaranteed to work (if you don't consider the extraordinary situations).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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