I have this snippet to make a read more button for content in a single product. it works well.
But I want the read button will disappear when the content is under the limit that I set (34 words).
What should I add to this code to make the button disappear if the word counts less then 34?
// Shorten product long description with read more button
function filter_the_content( $content ) {
// Only for single product pages
if( ! is_product() ) return $content;
// Set the limit of words
$limit = 34;
// Strip p tags if needed
$content = str_replace( array( '<p>', '</p>' ), '', $content );
// If the content is longer than the predetermined limit
if ( str_word_count( $content, 0 ) > $limit ) {
// Returns an associative array, where the key is the numeric position of the word inside the string and the value is the actual word itself
$arr = str_word_count( $content, 2 );
// Return all the keys or a subset of the keys of an array
$pos = array_keys( $arr );
// First part
$text = '<p>' . substr( $content, 0, $pos[$limit] ) . '<span id="dots">...</span>';
// More part
$text .= '<span id="more">' . substr( $content, $pos[$limit] ) . '</span></p>';
// Read button
$text .= '<button id="read-button"></button>';
$content = force_balance_tags( $text ); // needded
}
?>
<script type="text/javascript">
jQuery(document).ready( function ($) {
// Settings
var read_more_btn_txt = 'Read more';
var read_less_btn_txt = 'Read less';
// Selectors
var more = '#more';
var read_button = '#read-button';
var dots = '#dots';
// On load
$( more ).hide();
$( read_button ).html( read_more_btn_txt );
// On click
$( read_button ).on( 'click', function() {
if ( $( more ).is( ':hidden' ) ) {
$( more ).show();
$( dots ).hide();
$( read_button ).html( read_less_btn_txt );
} else {
$( more ).hide();
$( dots ).show();
$( read_button ).html( read_more_btn_txt );
}
});
});
</script>
<?php
return $content;
}
add_filter( 'the_content', 'filter_the_content', 10, 1 );