[wp-hackers] filter the_content without affecting the_excerpt

Dougal Campbell dougal at gunters.org
Wed Jul 20 00:24:05 UTC 2011


On Jul 19 2011 6:10 PM, Philip Walton wrote:
> So, I've spent some time digging through the source, and it appears 
> the wp_trim_excerpt() function applies 'the_content' filters to the 
> excerpt by default. And it looks like there's no getting around it.
>
> Can someone please explain the rational behind not differentiating the 
> two? Why should I be forced to apply my content filters to my excerpts 
> as well?
>
>
> On 7/19/11 12:38 PM, Philip Walton wrote:
>> In my theme I'm adding a filter to "the_content" to insert social 
>> sharing buttons at the beginning of each post, but then when I call 
>> the_excert() the text of those buttons is showing up.
>>
>> I know I can just write another filter on "get_the_excerpt" to remove 
>> them, but that just seems wrong.
>>
>> Is there a way to filter the_content without affecting the_excerpt?

Depending on your desired outcome, how about adding your own filters at 
a different priority? You can add a filter that runs at an earlier 
priority, and use that to remove the default filter.

   add_filter('get_the_excerpt', 'cancel_trim_excerpt', 5); // run at 
priority 5 instead of 10
   function cancel_trim_excerpt($content) {
     remove_filter('get_the_excerpt', 'wp_trim_excerpt');
     return $content;
   }

In your case, I think you said you're prepending share links, and the 
HTML is getting stripped from the excerpt, leaving you with bare text 
that has no purpose? How about:

   add_filter('get_the_excerpt', 'no_share_links', 5);

   function no_share_links( $content ) {
     remove_filter('the_content', 'add_my_share_links');
     return $content;
   }

   // fancy-schmancy: add the share links to the excerpt anyways:
   add_filter('the_excerpt', 'add_my_share_links', 20); // run after all 
the other filters

Is that what you're trying to do?

-- 
Dougal Campbell <dougal at gunters.org>
http://dougal.gunters.org/
http://twitter.com/dougal
http://twitual.com/


More information about the wp-hackers mailing list