6/30/2017 - 3:08 AM

Image/attachment lookup in WP All Import.

Image/attachment lookup in WP All Import.

Sometimes you might need to look up the attachment id for an imported image (or other media library file) to accommodate a third party plugin. You can use this code in the function editor.

/* Returns attachment ID for the given filename, path or URL. Argument can be a
 * URL or local file path because this will only look at the file basename. Ex - These
 * would return the same thing:
 * $id = img_id("myfile.jpg");
 * $id = img_id("http://domain.com/images/myfile.jpg");
function att_id($image_filename) {
    global $wpdb;
    $filename = pathinfo($image_filename, PATHINFO_FILENAME);
    $attachment = $wpdb->get_col($wpdb->prepare(
        "SELECT ID FROM $wpdb->posts WHERE post_type = 'attachment' 
        AND post_title LIKE '%s';", $filename));
    return (!is_array($attachment) || empty($attachment)) ? FALSE : $attachment[0];

You would invoke it in WP All Import like this:


Of course, you'd also need to add {my_image_url[1]} to the images section of your import so that the image is actually imported.

Note: WP All Import processes the sections of the import in roughly the same order you see on screen. For that reason you won't be able to reference an imported image in the body, but you will be able to reference it in the custom fields section (for example). See below.