tags:

views:

23

answers:

3

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?

+1  A: 
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.

RobertPitt
this actually causes the content to be displayed twice.
chris
yea it slipped my mind, you have to use `get_the_content()`
RobertPitt
A: 

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.

chris
can you just verify why you need to start an output buffer ?
RobertPitt
otherwise the content would be displayed. I just wanted to capture it into a variable. Maybe there's a wordpress function that does this by default but this works.
chris
you can use `get_the_content`
RobertPitt
A: 

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);
Gipetto