Support » Fixing WordPress » Need to get attachment ID by Image URL

  • Resolved Ganners

    (@ganners)


    I’m using a jquery script called Captify, it works by taking the alt tag of an image and displaying it as the alt tag on mouse over.

    I’m also using the header image theme plugin and this has no option to add or display the alt tag, and that’s fine as I can add the alt in the media browser.

    What I therefore need is a way to get the attachment ID of the header image and display its alt.

    The code below works, but this means I have to set the attachment ID manually (602). I’m sure my client wouldn’t want to do this so I’d like a way to make it dynamic. Are there any already-existing functions that I’m missing or should I create my own query?

    <img src="<?php header_image(); ?>"
    class="captify"
    width="<?php echo HEADER_IMAGE_WIDTH; ?>"
    height="<?php echo HEADER_IMAGE_HEIGHT; ?>" 
    
    alt="
    <?php
    $alt_text = get_post_meta(602, '_wp_attachment_image_alt', true);print $alt_text;
    ?>
    " />

    and the test site:
    VC News

    Thanks for any help!

    Mark

Viewing 4 replies - 16 through 19 (of 19 total)
  • Hi Guys,

    I’ve got an solution that may be usefull, because I’ve got some problems using the GUID as my search string sometimes I’ve got duplicated content, I don’t know why but I got it, so I developed this function to return any Post ID based in it’s url:

    function drfw_postID_by_url($url) {
    	global $wpdb;
    	$id = url_to_postid($url);
    	if($id==0) {
    		$fileupload_url = get_option('fileupload_url',null).'/';
    		if (strpos($url,$fileupload_url)!== false) {
    			$url = str_replace($fileupload_url,'',$url);
    			$id = $wpdb->get_var("SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '$url' AND wposts.post_type = 'attachment'");
    		}
    	}
    	return $id;
    }

    So drfw is just a prefix im using, if you guys have any problems using this functionlet me know so I can improve it.

    Thanks,

    Thanks webord,

    Very helpful right now. BTW: you may want to escape the url. For my purposes, I needed to.

    $id = $wpdb->get_var($wpdb->prepare("SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $url));

    Very good Idea Robcolburn,

    I’ve just forgot to prepare the data, my fault!

    But thanks.

    I would just like to see in the post gallery somewhere that says “Attachment ID = X.” Is this possible?

Viewing 4 replies - 16 through 19 (of 19 total)
  • The topic ‘Need to get attachment ID by Image URL’ is closed to new replies.