I'm displaying a preview of a post/page/cpt using a 'work-around' that i found. This 'work-around' gets the post content, trim it and render the trimmed content with it's html elements ( links, images etc.. ), so similar to the_content().

The mentioned work-around is this

$more = '...';
echo  force_balance_tags( html_entity_decode( wp_trim_words( htmlentities( $values["content"] ), 300, $more ) ) ); 
echo '<a href="'. $link . '" class="readMoreBtn">Read More</a>'

This little code

  • displays preview of the post correctly if the content doesn't get trimmed when a comment starts
  • breaks the html when it ends with a non-closed started comment <!--

i mean sometimes happens that the trimmed page content ends like this

<!-- wp:image...<a href="https://gudesign.org/thematic-nodes/giovannoni-prima-di-giovannoni/" class="readMoreBtn">Read More</a>

so i suppose that the image that was going to be displayed started but the comment has never been closed. This cause that the whole html code under that output get commented unitl it encounters a close comment tag -->.

As a solution for this i changed

Before: echo '<a href="'. $link . '" class="readMoreBtn">Read More</a>'

After: echo '<!-- --><a href="'. $link . '" class="readMoreBtn">Read More</a>'

So that the close comment tag is find instantly.

I supposed that the force_balance_tags could balance all the tags in the string, am i wrong?

There is a better way to solve this rather than adding <!-- --> right after the built preview's echo?

  • 1
    Can you rewrite the first sentence using different words? I do not believe the approach you've taken to excerpts is the correct one, you should instead turn the content into blocks, then you would not need to mess with HTML comments – Tom J Nowell Jan 17 at 20:07
  • @TomJNowell done. Do you mean calling html_entity_decode before the force_balance_tags ? If yes i've already tried this but the same error occurs – Mat.C Jan 17 at 20:22
  • No, I mean parsing the blocks themselves using the official API parse_blocks. Functions like html_entity_decode handle HTML comments by stripping them first before doing any processing, and the HTML comments came balanced in the content to begin with. Also HTML comments are not the same as tags – Tom J Nowell Jan 18 at 9:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.