How to Expand/Collapse WordPress Posts with jQuery


WordPress has the feature which makes the post “Condensable” for the main post view page, but sometimes that feature does not fulfill the requirement.

Expand/Collapse WordPress Posts

I’d like the user to have the option to expand the post that interests him while keeping him in the context of all the other post headlines. This is a very popular jQuery enhancement. Let’s take a look at how we’d do that. Set up a clean custom-jquery.js file in your theme and let’s get started.
First, hide the post content:

jQuery(".post .entry-content").hide();

Next, it would be very inefficient to have an editor add a control element to each post. So, we could add it to the theme’s post.php page, but then, the control would appear even if the user had JavaScript disabled. We want this
to degrade gracefully, it’s an enhancement after all.
If someone comes across this content in a mobile browser without JavaScript support or a text-only or text-to-speech browser, we’ll want them to just view the content as normal without any non-functional elements distracting them. We’ll use jQuery to add our control element. If JavaScript is disabled, it simply won’t appear.

jQuery(".post").after("<div class='openIt' style='border-top: 1px solid #666; color: #036; text-align:right; cursor:pointer;'>Expand</div>");

We now just need a nice way to show and hide the post’s content:

 jQuery(".openIt").click(function() {

Last, let’s make sure the instructions in the .openIt div update:


That’s it! This is very useful jQuery enhancement for WordPress. Let me know if you are facing any issues in the comments section below.

1 comment
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like