How to get image ID based on get_theme_mod image URL?

admin2025-06-03  3

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 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?

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/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?

Share Improve this question asked Feb 19, 2019 at 22:34 DamianDamian 971 gold badge1 silver badge11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748887766a314552.html

最新回复(0)