This requires a minor tweak to the existing code that instead of leaving out some of the $content
, keeps all of the $content
but shows only part of it until the read button is clicked.
Then it uses jQuery
which has control over the read more/less button where either all $content
or only part of it is shown.
NOTE: CSS (styling) and further jQuery adjustments are theme dependent. This answer contains the basis of a read more / less button. Each theme has different and specific requirements so further adaptation of the display/functionality must be provided by yourself
Explanation via comment tags provided in the code
// Shorten product long descrition 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 = 14;
// 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 );
