0

I have the following function:

function remove_images( $content ) {
    if( ( is_category() || is_archive() || is_home() ) && has_term( 'MyCat', 'category', $postID ) ) {
        $postOutput = preg_replace("/\< *[img][^\>]*[.]*\>/i","",$content,1);
    return $postOutput;
    }
}
add_filter( 'the_content', 'remove_images', 100 );

What it is meant to do is remove the first image in the_content() on thew index page (all listing pages) only for those posts in the MyCat category. What it is doing, instead, is removing the first image from the_content() on all posts for the index page, and removing the_content() altogether on all of the single pages. Any help would be appreciated. Thank you.

  • 1
    Is this code in full? Where does $postID come from? – Rarst Dec 21 '12 at 17:33
  • $postID = get_the_ID(); I defined it above the function. Could that be causing the problem? – sosukeinu Dec 21 '12 at 17:46
  • Yep, you need to define variables inside function (or declare them as global), in current form it will always be null. – Rarst Dec 21 '12 at 18:02
1

What it is doing, instead, is removing the first image from the_content() on all posts for the index page...

That's because that's what your callback is telling the filter to do. It returns true for all posts in your specified contexts (archive index, category index, blog posts index), not just for the first post in those indices.

...and removing the_content() altogether on all of the single pages.

That's because, if your conditional returns false, you don't return anything. You need to return $content; outside of your conditional.

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.