Skip to content

Instantly share code, notes, and snippets.

@Programmer095
Forked from m-thomson/att_id.md
Created August 21, 2017 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Programmer095/46834e3c36d6a588b8d03ab5deae76f2 to your computer and use it in GitHub Desktop.
Save Programmer095/46834e3c36d6a588b8d03ab5deae76f2 to your computer and use it in GitHub Desktop.
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:

[att_id({my_image_url[1]})]

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.

image-id-lookup

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment