I have a separate theme for my custom WP install that will be use for mobile users, in my case I need to change an html tag in all the excerpt instances but without altering the DB, I found this simple function that would be perfect but I can't get it to work, nothing's happening.

function replace_content_on_the_fly($text){
$replace = array(
    // 'words to find' => 'replace with this'
    '<p>' => '<div>',
    '</p>' => '</div>'
$text = str_replace(array_keys($replace), $replace, $text);
return $text;
add_filter('the_excerpt', 'replace_content_on_the_fly');

I added the above code in my theme function.php. Why doesn’t it work?


You code works where the function the_excerpt is used. It does not work when get_the_excerpt is used, which does not apply the the_excerpt filter. It applies get_the_excerpt instead.

Using get_the_excerpt will cause the filter to apply to both the cases since the_excerpt() uses get_the_excerpt().

Automatically generated excerpt content is a different thing since it is created by a filter on get_the_excerpt that strips the markup.

| improve this answer | |
  • In my index.php I have this <?php the_excerpt(); ?> and the excerpt is not auto generated, so if I change the filter to get_the_excerpt instead of the_excerpt that should work but I still see no changes. – Incognita Mundi Jun 29 '13 at 17:02
  • Excerpts are generated when I try it. Have you tried using TwentyTwelve or TwentyThirteen? – s_ha_dum Jun 29 '13 at 17:09
  • Ok I don't need to generate the excerpt, I have custom ones already created, I was now trying to get it to work on the_content using the default themes but same thing, doesn't seem to work, I even tried to replace the word sample with something else in a post instead of trying to alter an HTML tag but nothing is happening. – Incognita Mundi Jun 29 '13 at 17:20
  • After reinstalling WP and reimporting the DB the function started working on my theme! – Incognita Mundi Jun 29 '13 at 20:36

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.