Read more on the post page itself

I know how to use read more technique to only view an excerpt of the topic on the homepage and click on the read more icon to open the post and view the full content.

Can we do it on the post itself? When the visitor open the post page itself (not the homepage), only an excerpt is available and they should click on “read more” to view the full content.

2 Answers
2

The solution might depend on why exactly you want it to work that way on the post page. But probably the best way would be to do this on the client side.

Method with maximum height

Let’s say your post template has its content like this:

<div id="content"><?php the_content(); ?></div>

You need to add a button after this div, so it would become:

<div id="content"><?php the_content(); ?></div>
<button class="show-more">Show more</button>

Then you add CSS to only show the content up to specific height, in your style.css add:

#content { max-height: 100px; overflow: hidden; }
.show-more { margin-top: 15px; }

Finally, add a script that would show the full height of content and remove “show-more” button after it’s clicked:

jQuery(document).ready(function($) {
    $('.show-more').click(function() {
        $('#content').css('max-height', 'none');
        $(this).remove();
    });
});

It’s just a basic setup, so feel free to adjust the styles and the script as you’d like.

Here’s a link to the fiddle where you can try it out: https://jsfiddle.net/psxtur2L/

Method with replacing the content

If you want to specifically show the excerpt as a short version, you can do it this way.

In your template, you add both the excerpt and the content, and a button, like this:

<div id="excerpt"><?php the_excerpt(); ?></div>
<div id="content"><?php the_content(); ?></div>
<button class="show-more">Show more</button>

In CSS you just hide the content by default:

#content { display: none; }
.show-more { margin-top: 15px; }

And then you hide the excerpt and show the content when the user clicks on the button:

jQuery(document).ready(function($) {
    $('.show-more').click(function() {
        $('#excerpt').hide();
        $('#content').show();
        $(this).remove();
    });
});

Here’s a fiddle for that: https://jsfiddle.net/o7z2Lsks/

Note that the user can access full content without clicking the button if he’s using browser’s debugger tool, but I assume that it is not important. If you would need to make checks whether the user is logged in and so on, you should rather use AJAX, so it would require more additions to the code.

Leave a Comment