0

I'm trying to filter my content and on matches on flow I would like to change my html structure, but my rule doesn't really apply. I have the following filter which searches the first image of posts and on rule match attaching a css container. The preg_match_all is working but the str_replace doesn't

function imageFooter($content){

      global $post, $posts;

      preg_match_all('/<a.href="(.*?)"><img.*?src="(.*?)".*?><\/a>/', $post->post_content, $matches);
      $to_search = $matches[0][0];
      $replacement = '<div class="image_footer">'.$matches[0][0].'<span class="logo"></span></div>';
      str_replace($to_search , $replacement, $post->post_content);
      return $content;

    }

    add_filter('the_content',   'imageFooter');

2 Answers 2

0

Change,

str_replace($to_search , $replacement, $post->post_content);

to..

$content =  str_replace($to_search , $replacement, $post->post_content);
4
  • Thanks a lot. This was an ordinary big mistake what I made
    – fefe
    Commented Feb 15, 2013 at 15:06
  • No problem, also you are passing $content variable to your function by reference so you don't technically need your globals, you can of course just use $content.
    – Adam
    Commented Feb 15, 2013 at 15:10
  • Yes I have been changing theme as @s_ha_dum suggested
    – fefe
    Commented Feb 15, 2013 at 15:11
  • Good stuff.. all the best.
    – Adam
    Commented Feb 15, 2013 at 15:14
2

You haven't set $content to anything so it is just returning the same thing that was passed into the function. Read the doc's for str_replace. You should have:

$content = str_replace($to_search , $replacement, $post->post_content);

But why are you operating on $post->post_content? The post content is passed into the filter. You even have a parameter named $content that you aren't using. What you are doing is likely to cause trouble. Think about this.

Your site has 4 filters on the_content including yours.

  1. Uses $content
  2. Uses $content as modified by filter one, since they "chain".
  3. Uses $content as modified by the previous two filters.
  4. Your filter uses $post->content which is outside of the "chain". You've just wiped out all the preceding filters.

Also, you aren't using $posts at all.

Your code should be:

function imageFooter($content){
      preg_match_all('/<a.href="(.*?)"><img.*?src="(.*?)".*?><\/a>/', $content, $matches);
      $to_search = $matches[0][0];
      $replacement = '<div class="image_footer">'.$matches[0][0].'<span class="logo"></span></div>';
      $content = str_replace($to_search , $replacement, $content);
      return $content;
}

add_filter('the_content',   'imageFooter');

And you should be warned that using regex to parser HTML is very dicey business. It is easy to go wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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