Resize Image Wordpress Script

1

I found this script for wordpress, to get the image of the post and add it to the wordpress theme.

See the script:

function catch_that_image() {
global $post, $posts;
$first_img = '';
$new_img_tag = "";

ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post-   >post_content, $matches);
$first_img = $matches [1] [0];

if(empty($first_img)){ //Defines a default image with 0 width
$new_img_tag = "<img src='/images/noimage.jpg' width='0px' class='alignleft' />";
}

 else{
 $new_img_tag = "<img src='" .  $first_img . "' width='100px' height='100px'    class='alignleft' />";
}

return $new_img_tag;
}

end of script

This little code we added to draw the image somewhere in the theme.

    <?php echo catch_that_image() ?>

As you can see the script leaves the image scaled at 100x100, I would like to control the size of the image by this code:

      <?php echo catch_that_image() ?>

I need to leave the image on each page with different dimensions.

    
asked by anonymous 23.06.2015 / 16:48

1 answer

2

How about passing the dimensions by parameter?

function catch_that_image($w, $h) {
    global $post, $posts;
    $first_img = '';
    $new_img_tag = "";

    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_img = $matches [1] [0];

    if(empty($first_img)){ //Defines a default image with 0 width
        $new_img_tag = "<img src='/images/noimage.jpg' width='0px' class='alignleft' />";
    }

    else{
       $new_img_tag = '<img alt="' . $post->post_title . '" src="' . $first_img . '" width="' . $w . '" height="' . $h . '" class="alignleft" />';
    }

    return $new_img_tag;
}

Once this is done, just call the <?php echo catch_that_image(150, 150) ?> function, or any other values you want.

EDIT

I added the alt tag, using wordpress get_the_title() . Since this code is (it seems to me at least) out of the loop, the_title() would not work, as per documentation .

EDIT 2

After a more detailed analysis, it's much smarter to use $post->post_title than echo get_the_title($post->ID) . It took me a while to understand what I had said ...

    
23.06.2015 / 17:37