Make WordPress Core

Opened 9 years ago

Closed 9 years ago

Last modified 8 years ago

#29533 closed enhancement (wontfix)

wp_trim_words preserves HTML tags

Reported by: mekku's profile Mekku Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.1
Component: Formatting Keywords: reporter-feedback close
Focuses: Cc:

Description

Allows wp_trim_words() to preserve certain HTML tags.

Proposal:

wp_trim_words( $text, $max_words, $more, $allowed_tags );

Change History (6)

#1 @karpstrucking
9 years ago

  • Keywords reporter-feedback added

Hi Mekku,

Can you provide an example use-case? I suspect there will be a way to accomplish what you want without requiring a change to core. For example, if you are calling wp_trim_words() directly in your theme/plugin, you could just include and use your own modified version my_wp_trim_words(). If you are wanting to modify the standard post excerpt to include certain HTML elements, you can make use of the wp_trim_excerpt filter

#2 @nacin
9 years ago

  • Keywords close added

I think wp_trim_words() is already pretty complicated (3 arguments). This would also make it significantly more complicated, because it's not just about removing the call to wp_strip_all_tags() — it'd also be about trimming it to the correct number of words regardless of HTML tags, and then returning those words with the HTML tags in tact. (And with balanced tags, no less.) I don't want to mess with any of this in core as we have no use for it.

#3 @thudfactor
9 years ago

Hey, I managed to do something like this by stringing a few things together. You encode the tags, trim the string, decode the tags, then run WP's force_balance_tags ( http://codex.wordpress.org/Function_Reference/force_balance_tags ) to make sure any tags closed on the wrong side of the trim are balanced.

For example:

    force_balance_tags(html_entity_decode(wp_trim_words(htmlentities($text))));

My real-life use case for this is outputting an "excerpt" of an ingested RSS feed in a template.

#4 @MikeHansenMe
9 years ago

I agree with Nacin that it is not a good idea to further modify wp_trim_words. I think the name itself implies it is for words/text not html. I think an option would be to introduce a new function for this use case.

#5 @helen
9 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to wontfix
  • Status changed from new to closed

#6 @startsmartnow
8 years ago

@thudfactor - Thanks. Your force_balance_tags solution was just the thing I needed.

Note: See TracTickets for help on using tickets.