Attached Image Info

I have to give it to jredfern, not only did he get pissed enough to offer a solution years before me, his code is prettier, using stdOjects instead of arrays like I did. I’ll put both below so you can decide for yourself.

Jredfern’s Verison

function get_image_by_id($image_id, $size) {
	$image = get_post($image_id);

	$imageObj = array();
	$imagearray = wp_get_attachment_image_src($image->ID, $size, false);
	$imageObj['src'] = $imagearray[0];
	$imageObj['width'] = $imagearray[1];
	$imageObj['height'] = $imagearray[2];
	$imageObj['id'] = $image->ID;
	$imageObj['title'] = $image->post_title;
	$imageObj['caption'] = $image->post_excerpt;
	$imageObj['description'] = $image->post_content;
	$imageObj['alt'] = get_post_meta($image->ID, '_wp_attachment_image_alt', true);

	return $imageObj;

Pretty slick, I must say.

Here’s was my prior attempt:

function wp_get_attachment_atts( $attachment_id='' ) {
	if( empty( $attachment_id ) ) $attachment_id = get_the_ID(); // use current id if none
	if( !wp_attachment_is_image( $attachment_id ) ) return false; // check if attachment
	
	$attachment = get_post( $attachment_id ); // get attachment
	
	if( !$attachment ) return false;
	else return array(
		'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
		'caption' => $attachment->post_excerpt,
		'description' => $attachment->post_content,
		'href' => get_permalink( $attachment->ID ),
		'parent_id' => $attachment->post_parent,
		'src' => $attachment->guid,
		'title' => $attachment->post_title );

Anyway, hope these workaround can make like easier, at least until they get fixed for real.

One Thought on “3 WordPress Hacks to Unlock Some Much-Needed Features

  1. Shariq on April 18, 2013 at 12:38 am said:

    Hi,

    Thanks for the great post. However, I am having trouble implementing it.
    I am trying to change the look of my searchform. It basically needs to have two text fields. I want this ti be in form of a plugin, which anyone can activate. SO obviously I do not have any control over searchform.php. This made me look at your code snippet.

    I copied your code as it is and added a filter like:
    add_filter(‘get_search_form’,’shinra_searchform’);
    However, the code seems to go in an infinite loop. I put an echo statement after lines 11 and 12. The one after 12 never gets printed while the one after line 11 keeps on getting printed continously.

    I tried changing the filter to pass the argument to:
    1. add_filter(‘get_search_form’,shinra_searchform(true),1);
    2. add_filter(‘get_search_form’,shinra_searchform(false),1);
    3. add_filter(‘get_search_form’,shinra_searchform($echo),1);
    But none of these work.

    Can you please help me out.

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation