wordpress check if post has image attachment

In custom theme checking post image is really useful because old post has no featured image set. Using our code wordpress check if post has image attachment. Just use following code the check for image in wordpress post.

wordpress check if post has image attachment

Copy paste the following function in functions.php file.


function check_image(){
$content = $post->post_content;
$all_images = '~<img [^>]* />~';

preg_match_all( $all_images, $content, $pics );

// Check to see if we have at least 1 image
$all_pics = count($pics[0]);

if ( $all_pics > 0 ) {
// Your post have one or more images.
return true
} else {
return false;

}

wordpress check if post has image attachment

wordpress check if post has image attachment

In post loop just add or call this function. This function will return the true or false.

Add a Comment

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