0

I'm trying to use wp_get_attachment_image function to insert image. For that I need use image ID. So now I need to know how to get this ID by image URL taken from get_theme_mod from WP Customization API.

So:

$image_src = get_theme_mod('header_logo', '');
$image_id = HOW TO GET ID FROM $image_src ??
echo wp_get_attachment_image( $image_id, 'logo' );

I found this solution https://stackoverflow.com/questions/25671108/get-attachment-id-by-file-path-in-wordpress/31743463 so I was trying:

// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
    global $wpdb;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
        return $attachment[0]; 
}

// set the image url
$image_url = get_theme_mod('header_logo', '');

// store the image ID in a var
$image_id = pippin_get_image_id($image_url);

// print the id
echo $image_id;

// final image
echo wp_get_attachment_image( $image_id, 'logo' );

but still nothing. Any ideas?

1 Answer 1

0

WordPress has a built-in function for this: attachment_url_to_postid().

More info from a Stack Overflow question: Get Attachment ID by File Path in WordPress.

1
  • 'attachment_url_to_postid' is what I'm looking for, thanks!
    – Damian
    Feb 19, 2019 at 22:56

Your Answer

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

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