0

I'm trying to make a Wordpress function and currently I have this in my functions.php file:

 function find_my_image($content) {
     if(is_single()) {

    if (preg_match('#(<img.*?>)#', $content, $result)){

        $content .= '<p>Image has been found</p>';

    }
    else{

        $content .= '<p>Sorry, no image here!</p>';

    }

return $content;

 }
 }

add_filter('the_content', 'find_my_image');

The function works perfectly on a single post page, but my index.php is now blank (only the titles of the posts are displayed, but no post content). I tried removing:

add_filter('the_content', 'find_my_image');

from function.php, but that's stops the function from executing on my single.php. Also I tried using this (I don't know if it's correct):

 if(is_single()) {

     add_filter('the_content', 'find_my_image');

}

But that's just cancels the function on single.php. My guess is that add_filter('the_content', 'find_my_image'); is the problem here, but I can't figure it out, so can anyone help me out a bit?

1

You need to return content from filter function.

function find_my_image( $content ) {
    if( is_single() ) {
        if ( preg_match('#(<img.*?>)#', $content, $result ) ){
            $content .= '<p>Image has been found</p>';
        }
        else{
            $content .= '<p>Sorry, no image here!</p>';
        }
    }
    return $content;
}

add_filter( 'the_content', 'find_my_image' );
  • @Rajeev Vyas it was silly mistake by me, thanks for fixing it. – Mentalhead Apr 5 '13 at 12:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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