Curtis Cook
Curtis Cook

Reputation: 417

Trying to grab an Image from a Wordpress Post

Ive cobbled together the following code and it works, but it feels too hacky:

function get_my_img() {
if($imgs = get_posts(array(
    'post_parent' => get_the_ID(),
    'post_type' => 'attachment',
    'numberposts' => 1,
    'post_mime_type' => 'image',
    'orderby' => 'menu_order',
    'order' => 'DESC'
    ))){
foreach($imgs as $img) {
    $img_med = wp_get_attachment_image($img->ID,'medium');
    }
foreach($imgs as $img) {
    $img_larg = wp_get_attachment_image($img->ID,'large');
    }
if (preg_match('/<img.+?src(?: )*=(?: )*[\'"](.*?)[\'"]/si', $img_larg, $img_r)){
    echo '<a class="myimage" href="' . $img_r[1] .'">' . $img_med .'</a>';} 
    }
}

I'm pretty sure there is a far simpler way to do this that I've completely overlooked.

In essence, when this function is called inside the loop, it outputs the last image (attached) in the current post in it's medium size wrapped in a link to its large size.

Any insight Would be greatly appreciated.

Upvotes: 0

Views: 82

Answers (2)

alesub
alesub

Reputation: 1492

The preg_match() stuff is not necessary. If you print $img_med and $img_larg, you'll see that they're arrays, containing three elements: The path to the image, the width and the height. So you can output the html you need with those.

Upvotes: 1

chrisn
chrisn

Reputation: 2125

Much simpler to do:

function get_my_img() {
if($imgs = get_posts(array(
    'post_parent' => get_the_ID(),
    'post_type' => 'attachment',
    'numberposts' => 1,
    'post_mime_type' => 'image',
    'orderby' => 'menu_order',
    'order' => 'DESC'
    ))){

    $img_med = wp_get_attachment_image($imgs[0]->ID,'medium');
    $img_larg = wp_get_attachment_image_src($imgs[0]->ID,'large');

    echo '<a class="myimage" href="' . $img_larg[0] .'">' . $img_med .'</a>';
} 
}

Upvotes: 1

Related Questions