I am using the following code and toolset shortcode to trim text in the custom excerpt and still keep formatting but the text is shown with HTML tags. What could I be missing?
If I use wp_trim_words it shows the text but strips all formatting. If I use the code below, it keeps the formatting AND the HTML tags.
<?php global $wpdb;
global $post;
$project_prompt_description = types_render_field("prompt-description", array( ));
//echo $project_prompt_description;
$length = 30;
if (strlen($project_prompt_description) > $length) {
$project_prompt_description = substr($project_prompt_description, 0, $length) . '…';
}
echo $project_prompt_description;
//echo wp_trim_words( $project_prompt_description, 30, '...' );
?>
Hello and thank you for contacting Toolset support.
I assume that you meant by formatting the effect of some HTML tags, like "strong" or something else, right?
If that's the case, I'll suggest using strip_tags function before line 9 to remove HTML tags, but to keep some of them, that has to be passed in the second argument. For example:
$length = 30;
if (strlen($project_prompt_description) > $length) {
// keep <strong> and <em> tags
$project_prompt_description = strip_tags( $project_prompt_description, array('strong', 'em'));
$project_prompt_description = substr($project_prompt_description, 0, $length) . '…';
}
hidden link
However, this is not guaranteed to work as expected, because you may be removing the closing tag with the substr function.
The excerpt is by design meant to be stripped and hold only text. So, I don't think there would be a simple generic solution.
Jamal,
What if I use a custom field instead of an excerpt?
Explanation -
WYSIWYG custom field with pre-filled data to encourage users to enter into a certain order - hidden link
The field appears as normal in the form -
Form setup - hidden link
Front-end - hidden link
I have no problem with the format when I want the whole field to be visible. Like this - hidden link
However, when I want to show only a section of the field using trim, it loses all formatting. Use case - hidden link
Thoughts?
Whenever you use trimming functions from PHP or WordPress, you will get the formatting lost. That's a design decision on how those functions work. If you need to keep the formatting, trimming and excerpt functions are most probably not the correct choice.
What if you split the field into multiple fields(context, objective, and format). Use single line fields if you don't need the user to use a WYSIWYG field. Then, you can have your own format markup for the displaying, you can programmatically decide how many words to display, and if you should display the "objective" and "format". Does it make sense?
That sounds right. Thanks.
My issue is resolved now. Thank you!