This is my code to get the first image:

function get_post_first_image() {
global $post, $posts;
$first_img  = '';
$content    = get_the_content();
$content    = apply_filters( 'the_content', $content );
$output     = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches); // You must replace data-original to str if you disabled lazy-load images
$first_img  = $matches[1][0];
    $first_img = "";
return $first_img;

how can convert this code to make its search on the post content for any image width and height more than 500px? Note: search for the all content not search for the first post only. Can getimagesize help on this?

1 Answer 1


You can run your $matches through the getimagesize() function to check it's dimensions, the problem is this function requires a path to the image but your content will provide full URL's so you'll need to see if the image is also saved in your media library and if so grab the relative path only. If a lot of the images are from 3rd party sites it's more complex as you'll need to fetch the image or you would need to use javascript instead.

Example if your images are hosted on your own site:

$images = array();

foreach ( $matches[1] as $match ) {

    $attachment_id = attachment_url_to_postid( $match );

    if ( $attachment_id ) {

        $path = get_attached_file( $attachment_id );

        list( $width, $height ) = getimagesize( $path );

        if ( $width > 500 && $height > 500 ) {





var_dump( $images );
  • Note that as far as I remember that API function doesn't handle generated image sizes. Generic reliable reversal of image URL is far from trivial, I have answer on that somewhere around here....
    – Rarst
    Commented Jul 28, 2017 at 19:26
  • Thank you but I can't use get_attached_file because the image that uploaded in the post is uploaded through custom upload system on the frontend, not from wp admin, hope you understand me.
    – Youro
    Commented Jul 28, 2017 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.