Skip to content

Instantly share code, notes, and snippets.

@ericrasch
Last active July 4, 2017 03:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericrasch/5680839 to your computer and use it in GitHub Desktop.
Save ericrasch/5680839 to your computer and use it in GitHub Desktop.
Create collapsable content sections using WordPress' the_content().
/* =BEGIN: Add Class to first Paragraph in WordPress the_content();
Source: http://wordpress.stackexchange.com/a/51682/28826
---------------------------------------------------------------------------------------------------- */
function first_paragraph($content){
// Finding the 1st p tag and adding a class.
$content = preg_replace('%<p([^>]+)?>%', '<p$1 class="intro">', $content, 1);
// Finding the 1st closing p tag and adding a div tag to the rest of the content so we can separate it.
$content = preg_replace('%</p>%', '</p> <div id="collapsable-content">', $content, 1);
// Appending content to the_content (closing the div tag). Source: http://wordpress.stackexchange.com/a/28268/28826
$content .= '</div> <p id="collapsable-link"><a href="#" class="read-more"><span>Read More</span></a></p>';
return $content;
}
add_filter('the_content', 'first_paragraph');
jQuery(document).ready(function($) {
$('#collapsable-content').slideToggle();
$('#collapsable-link a').click( function() {
$('#collapsable-content').slideToggle();
$(this).find('span').html('Show Less');
});
});
<div class="entry-content">
<?php the_content(); ?>
</div><!-- .entry-content -->
@jimmynotjim
Copy link

This will fix the text not changing back. Notice I changed .click to .on('click',... The former was deprecated and .on is suggested use from now on. It's basically the same thing, they just condensed a few actions down to one.

jQuery(document).ready(function($) {
  var contentState = 'closed';
  var destination = $('#collapsable-content').offset().top;

  $('#collapsable-content').slideToggle();
  $('#collapsable-link a').on('click', function(e) {
    e.preventDefault();
    $('#collapsable-content).slideToggle();

    if (contentState === 'closed') {
      contentState = 'open';
      $(this).find('span').text('Show Less');
    } else {
      contentState = 'closed';
      $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination-20}, 500 );
      $(this).find('span').text('Show More');
    }
  });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment