phpjquerycsswordpresscharactercount

How to make jQuery or WordPress PHP that counts characters then finds last space and replace all content after with "..."


I need to limit the amount of text displayed within a div from a WordPress Custom Field.

<?php $textcount = strlen(get_field('custom_quote')); ?>
<?php if ( $textcount > 250 ) : ?>
    <?php the_field('custom_quote'); ?>
<?php else : ?>
    <?php the_field('custom_quote'); ?>
<?php endif ?>

Want this: (351 Characters With Spaces) →

Prow scuttle parrel provost Sail ho shrouds spirits boom mizzenmast yardarm. Pinnace holystone mizzenmast quarter crow's nest nipperkin grog yardarm hempen halter furl. Swab barque interloper chantey doubloon starboard grog black jack gangway rutters. Deadlights jack lad schooner scallywag dance the hempen jig carouser broadside cable strike colors.

To find the space right before 250 Characters and then add the string value "..." in place of the " ". like this →

Prow scuttle parrel provost Sail ho shrouds spirits boom mizzenmast yardarm. Pinnace holystone mizzenmast quarter crow's nest nipperkin grog yardarm hempen halter furl. Swab barque interloper chantey doubloon starboard grog black jack gangway...

I'm not trying to limit the character count of the Custom Field because I need it to render the max text on a desktop display and then limit the text on a @media(max-width: 768px){}


Solution

  • You this wp_trim_words(). check below code.

    <?php $textcount = strlen(get_field('custom_quote')); ?>
    <?php if ( $textcount > 250 ) : ?>
        <?php echo wp_trim_words( get_field('custom_quote'), 33, '...' ); ?>
    <?php else : ?>
        <?php the_field('custom_quote') ?>
    <?php endif ?>