I would like to make an if statement that tests if a post has images in them. If they do I want them to do one thing and if not I want them to do something else.
Can someone guide me in the right direction?
I would like to make an if statement that tests if a post has images in them. If they do I want them to do one thing and if not I want them to do something else.
Can someone guide me in the right direction?
if(($c = get_the_content()) && strstr('<img',$c))
{
//has an image / you can use $c saves calling the function again
}else
{
//No image.
}
that's the quickest way to do it, may not be 100% accurate thou.
Thx
I ended up using
<?php
ob_start();
the_content();
$content = ob_get_clean();
if(!strpos($content, "<img")) {
the_content();
}else{
echo '<img src="' . catch_that_image() . '" alt=""/>';
}
?>
catch_that_image() is a custom function I found that displays only the image from a post.
Why not just use the built in featured image functionality?
// in functions.php
add_image_size('my-custom-image-size', width, height);
// in the template
if (has_post_thumbnail()) {
the_post_thumbnail('my-custom-image-size');
} else {
the_content();
}
//or via a filter
function my_image_replacement($the_content) {
global $post;
if (has_post_thumbnail()) {
$the_content = get_the_post_thumbnail($post->ID, 'my-custom-image-size');
// other stuff as necessary
}
return $the_content;
}
add_filter('the_content', 'my_image_replacement', 11);