wordpress check if post has image attachment

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.

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

Leave a Reply

Your email address will not be published.