Skip to content

Instantly share code, notes, and snippets.

@anneallen
Created May 11, 2014 20:21
Show Gist options
  • Select an option

  • Save anneallen/ef54c3b34bb5c6bee7b2 to your computer and use it in GitHub Desktop.

Select an option

Save anneallen/ef54c3b34bb5c6bee7b2 to your computer and use it in GitHub Desktop.
Add a read more toggle
function toggle_shorten_string($string, $wordsreturned)
/* Returns the first $wordsreturned out of $string. If string
contains more words than $wordsreturned, the entire string
is returned.*/
{
$retval = $string; // Just in case of a problem
$array = explode(".", $string);
/* Already short enough, return the whole thing*/
$c = count($array);
$strlength =
$link ='<a class="read-more-show hide" href="#">Read More</a>'; //this link is 53 characters long
if (count($array)<=$wordsreturned)
{
$retval = $string;
}
/* Need to chop of some words*/
else
{
array_splice($array, $wordsreturned);
$retval = implode(".", $array)." $link";
$strlength = strlen($retval)-53;
$extra = substr($string,$strlength);
}
return $retval.' <span class="read-more-content">'.$extra.' <a class="read-more-hide hide" href="#">Read Less</a></span>';
/***Now add the following JS***/
/**Props to Josh Blackwood and his codepen http://codepen.io/JoshBlackwood/pen/pEwHe*/
// Hide the extra content initially, using JS so that if JS is disabled, no problemo:
$('.read-more-content').addClass('hide')
$('.read-more-show, .read-more-hide').removeClass('hide')
// Set up the toggle effect:
$('.read-more-show').on('click', function(e) {
$(this).next('.read-more-content').removeClass('hide');
$(this).addClass('hide');
e.preventDefault();
});
// Changes contributed by @diego-rzg
$('.read-more-hide').on('click', function(e) {
var p = $(this).parent('.read-more-content');
p.addClass('hide');
p.prev('.read-more-show').removeClass('hide'); // Hide only the preceding "Read More"
e.preventDefault();
});
//And use as a function as per in this shortcode....
add_shortcode('sc-brandposts', 'get_brandposts');
function get_brandposts($atts){
extract(shortcode_atts(array(
'brandname' => '',
), $atts));
$my_query = new WP_Query(array(
'post_type'=> array( 'brand'),
'orderby' => 'date',
'order'=> 'DESC',
'posts_per_page'=>-1,
'brand_tax' =>$brandname
));
$returnstring='<div class="brand-summary">';
while ($my_query->have_posts()) : $my_query->the_post();
$returnstring.='<h4>About '.get_the_title().'</h4>';
$string= get_the_content();
$returnstring.= toggle_shorten_string($string, 4);
endwhile;
$returnstring.='</div>';
return $returnstring;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment